hysteria-orm 10.9.6 → 10.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cli.js +46 -32
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +26 -26
- package/lib/index.cjs.map +1 -1
- package/lib/index.js +26 -26
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import Ce,{publicEncrypt,privateDecrypt,randomBytes}from'crypto';import Le from'dayjs';import zp from'dayjs/plugin/customParseFormat.js';import Yp from'dayjs/plugin/timezone.js';import Gp from'dayjs/plugin/utc.js';import {format}from'sql-formatter';import {highlight}from'sql-highlight';import {PassThrough,Readable}from'stream';import kr from'fs';import mt from'path';import {fileURLToPath,pathToFileURL}from'url';import {createRequire}from'module';var Fp=Object.defineProperty;var nl=i=>{throw TypeError(i)};var te=(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 sl=(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&&Fp(t,e,o),o};var Vp=(i,t,e)=>t.has(i)||nl("Cannot "+e);var il=(i,t,e)=>t.has(i)?nl("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e);var al=(i,t,e)=>(Vp(i,t,"access private method"),e);var h=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function Jp(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 Hp(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function V(i,t){return t==="preserve"?i:t==="snake"?Jp(i):t==="camel"?Hp(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}Le.extend(Gp);Le.extend(Yp);Le.extend(zp);var se=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=Le(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()}},ft=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new h("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?Le(i,t):Le(i);if(!r.isValid())throw new h("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch(r){throw new h("DateUtils::parseDate","FAILED_TO_PARSE_DATE",r)}},He=(i=new Date)=>Le(i).utc().format("YYYY-MM-DD HH:mm:ss");var ll=(i,t)=>{try{let e=Ce.createHash("sha256").update(i).digest(),r=Ce.randomBytes(16),o=Ce.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 h("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},ul=(i,t)=>{try{let e=Ce.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=Ce.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),u=l.update(a,"hex","utf8");return u+=l.final("utf8"),u}catch(e){throw new h("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},dl=(i,t)=>{try{let e=Ce.randomBytes(32),r=Ce.randomBytes(16),o=Ce.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new h("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},cl=(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=privateDecrypt(i,Buffer.from(o,"hex")),a=Ce.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 h("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};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 Fr="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jr=Fr.length,tf=10,rf=16,of=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%jr;e=Fr.charAt(o)+e,i=(i-o)/jr;}return e},nf=i=>{let t=randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=Fr.charAt(o%jr);}return e},ml=()=>{let i=Math.floor(Date.now()/1e3),t=of(i,tf),e=nf(rf);return t+e};function Ur(i){return i.replace(/^[`"]|[`"]$/g,"")}function Vr(i,t,e){if(!i.includes(".")){let n=Ur(i);return `${t}.${n}`}let[r,o]=i.split(".");return r=Ur(r),o=Ur(o),r!==e?i:o==="*"?`${t}.*`:`${t}.${o}`}function N(i){return typeof i=="function"?i():i}var L=(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]=L(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]=L(o,t);}return e};var we=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var Dt=class extends we{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var It=class extends we{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Pt=class extends we{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var $t=class extends we{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 sf(i){return i.endsWith("ies")?i.slice(0,-3)+"y":i.endsWith("sses")||i.endsWith("shes")||i.endsWith("ches")||i.endsWith("xes")||i.endsWith("zes")?i.slice(0,-2):i.endsWith("s")&&!i.endsWith("ss")?i.slice(0,-1):i}var Et=Symbol("columns"),ze=Symbol("primaryKey"),fe=Symbol("relations"),vt=Symbol("indexes"),Bt=Symbol("uniques"),Qt=Symbol("checks"),xe=i=>`${sf(i)}_id`,Kt=(i,t)=>`idx_${i}_${t}`,ue=(i,t)=>`uq_${i}_${t}`,X=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,De=(i,t)=>`pk_${i}_${t}`,pl=(i,t)=>{let e=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_|_$/g,"").toLowerCase();return `chk_${i}_${e}`.substring(0,63)};function Jr(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(vt,e.prototype)||[];o.push({columns:r,name:t??Kt(e.table,r.join("_"))}),K.defineMetadata(vt,o,e.prototype);}}function Hr(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=K.getMetadata(Bt,e.prototype)||[];o.push({columns:r,name:t??ue(e.table,r.join("_"))}),K.defineMetadata(Bt,o,e.prototype);}}function zr(i,t){return e=>{let r=K.getMetadata(Qt,e.prototype)||[];r.push({expression:i,name:t??pl(e.table,i)}),K.defineMetadata(Qt,r,e.prototype);}}var fl=Symbol("viewStatement");function O(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(K.getMetadata(ze,e))throw new h("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");K.defineMetadata(ze,r,e),K.defineMetadata(ze,r,e.constructor);}let n=i.databaseName??V(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??De(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}},a=K.getMetadata(Et,e)||[];a.push(s),K.defineMetadata(Et,a,e);}}O.primary=lf;O.date=Cf;O.datetime=Rf;O.timestamp=Mf;O.time=_f;O.boolean=qf;O.json=Of;O.uuid=pf;O.ulid=ff;O.integer=df;O.bigInteger=gf;O.float=uf;O.decimal=bf;O.increment=cf;O.bigIncrement=mf;O.string=yf;O.text=hf;O.binary=Tf;O.enum=wf;O.encryption={symmetric:Sf,asymmetric:Nf};function lf(i={}){return O({...i,primaryKey:true})}function uf(i={}){return O({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?Number.parseInt(t):Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function df(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)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function cf(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)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function mf(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)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function pf(i={}){return O({type:"uuid",...i,prepare:t=>t||Ce.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function ff(i={}){return O({type:"ulid",...i,prepare:t=>t||ml(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function yf(i={}){return O({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function hf(i={}){return O({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function gf(i={}){return O({type:"bigint",...i,serialize:t=>{if(t!==void 0){if(t===null)return null;if(typeof t=="number")return t;if(typeof t=="string")return Number.parseInt(t);if(typeof t=="bigint")return Number(t)}},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function bf(i={}){return O({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function Tf(i={}){return O({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function wf(i,t={}){return O({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Sf(i){return O({...i,prepare:t=>t&&ll(i.key,t),serialize:t=>t&&ul(i.key,t)})}function Nf(i){return O({...i,prepare:t=>t&&dl(i.publicKey,t),serialize:t=>t&&cl(i.privateKey,t)})}function qf(i={}){return O({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function Cf(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=u=>u?e?se(new Date,"DATE_ONLY",t):typeof u=="string"?u:se(u,"DATE_ONLY",t):r?se(new Date,"DATE_ONLY",t):null,l=u=>{if(u!==void 0)return u===null?null:ft(u,void 0,t)};return O({type:"date",...s,autoUpdate:e,prepare:u=>{let d=a(u);return o?o(d):d},serialize:u=>{let d=l(u);return n?n(d):d},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...s.openApi||{}}})}function Rf(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",u=e??t!==void 0,d=c=>c?r?se(new Date,"ISO",l):typeof c=="string"?c:se(c,"ISO",l):o?se(new Date,"ISO",l):null,p=c=>{if(c!==void 0)return c===null?null:ft(c,void 0,l)};return O({type:"datetime",...a,withTimezone:u,autoUpdate:r,prepare:c=>{let m=d(c);return n?n(m):m},serialize:c=>{let m=p(c);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...a.openApi||{}}})}function Mf(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",u=e??t!==void 0,d=c=>c?r?se(new Date,"TIMESTAMP",l):typeof c=="string"?c:se(c,"TIMESTAMP",l):o?se(new Date,"TIMESTAMP",l):null,p=c=>{if(c!==void 0)return c===null?null:ft(c,void 0,l)};return O({type:"timestamp",...a,withTimezone:u,autoUpdate:r,prepare:c=>{let m=d(c);return n?n(m):m},serialize:c=>{let m=p(c);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...a.openApi||{}}})}function _f(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=u=>u?e?se(new Date,"TIME_ONLY",t):typeof u=="string"?u:se(u,"TIME_ONLY",t):r?se(new Date,"TIME_ONLY",t):null,l=u=>{if(u!==void 0)return u===null?null:ft(u,void 0,t)};return O({type:"time",...s,autoUpdate:e,prepare:u=>{let d=a(u);return o?o(d):d},serialize:u=>{let d=l(u);return n?n(d):d},openApi:{type:"string",format:"time",description:"HH:mm:ss",...s.openApi||{}}})}function Of(i={}){return O({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function yl(i){try{return K.getMetadata(Et,i.prototype)||[]}catch{return []}}function hl(i,t,e){return((r,o)=>{let n=()=>xe(i().table),s=()=>{let u=r.constructor.table,d=t||n();return X(u,d,i().table)},a={type:"belongsTo",columnName:o,model:i,foreignKey:t?String(t):n,constraintName:e?.constraintName??s,onUpdate:e?.onUpdate,onDelete:e?.onDelete},l=K.getMetadata(fe,r)||[];l.push(a),K.defineMetadata(fe,l,r);})}function gl(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(fe,e)||[];s.push(n),K.defineMetadata(fe,s,e);})}function bl(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(fe,e)||[];s.push(n),K.defineMetadata(fe,s,e);})}function Tl(i,t,e,r){return((o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",u=typeof t=="string"?t:()=>t().table,d=o.constructor.table,p=()=>xe(d),c=()=>xe(i().table),m=()=>X(N(u),s?String(s):p()),g={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??m,foreignKey:s?String(s):p,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:d,throughModel:u,leftForeignKey:s?String(s):p,rightForeignKey:a?String(a):c,wasModelProvided:l}},f=K.getMetadata(fe,o)||[];f.push(g),K.defineMetadata(fe,f,o);})}function wl(i){return K.getMetadata(fe,i.prototype)||[]}function Sl(i){return (K.getMetadata(fe,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 Dt(l,n,a);case "hasOne":return new Pt(l,n,a);case "hasMany":return new It(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new h("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=o();return new $t(u,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:N(e.manyToManyOptions.throughModel),leftForeignKey:N(e.manyToManyOptions.leftForeignKey),rightForeignKey:N(e.manyToManyOptions.rightForeignKey)});default:throw new h("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Nl(i){return K.getMetadata(ze,i)||K.getMetadata(ze,i.prototype)}function ql(i){return K.getMetadata(vt,i.prototype)||[]}function Cl(i){return K.getMetadata(Bt,i.prototype)||[]}function Rl(i){return K.getMetadata(Qt,i.prototype)||[]}var Ie=class{};Ie.modelCaseConvention="camel",Ie.databaseCaseConvention="snake";var de=class{};de.columns=new WeakMap,de.byName=new WeakMap,de.byDatabaseName=new WeakMap;var Me=class extends Ie{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");if(t&&"value"in t)return t.value;throw new Error(`Table name not set for model "${this.name}". Use defineModel() to create models.`)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Nl(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=de.columns.get(this);return t||(t=yl(this),de.columns.set(this,t)),t}static getColumnsByName(){let t=de.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),de.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=de.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),de.byDatabaseName.set(this,t)),t}static getRelations(){return wl(this)}static getIndexes(){return ql(this)}static getUniques(){return Cl(this)}static getChecks(){return Rl(this)}};Me.softDeleteColumn="deletedAt",Me.softDeleteValue=He();function W(i){return {_phantom:void 0,_apply:i}}function F(i={}){return W((t,e)=>{O(i)(t,e);})}F.primary=function(t={}){return W((e,r)=>{O.primary(t)(e,r);})};F.string=function(t){return W((e,r)=>{O.string(t??{})(e,r);})};F.text=function(t){return W((e,r)=>{O.text(t??{})(e,r);})};F.integer=function(t){return W((e,r)=>{O.integer(t??{})(e,r);})};F.bigInteger=function(t){return W((e,r)=>{O.bigInteger(t??{})(e,r);})};F.float=function(t){return W((e,r)=>{O.float(t??{})(e,r);})};F.decimal=function(t){return W((e,r)=>{O.decimal(t??{})(e,r);})};F.increment=function(t={}){return W((e,r)=>{O.increment(t)(e,r);})};F.bigIncrement=function(t={}){return W((e,r)=>{O.bigIncrement(t)(e,r);})};F.boolean=function(t){return W((e,r)=>{O.boolean(t??{})(e,r);})};F.date=function(t){return W((e,r)=>{O.date(t??{})(e,r);})};F.datetime=function(t){return W((e,r)=>{O.datetime(t??{})(e,r);})};F.timestamp=function(t){return W((e,r)=>{O.timestamp(t??{})(e,r);})};F.time=function(t){return W((e,r)=>{O.time(t??{})(e,r);})};F.json=function(t){return W((e,r)=>{O.json({type:"json",...t??{}})(e,r);})};F.jsonb=function(t){return W((e,r)=>{O.json(t??{})(e,r);})};F.uuid=function(t){return W((e,r)=>{O.uuid(t??{})(e,r);})};F.ulid=function(t){return W((e,r)=>{O.ulid(t??{})(e,r);})};F.binary=function(t){return W((e,r)=>{O.binary(t??{})(e,r);})};F.enum=function(t,e){return W((r,o)=>{O.enum(t,e??{})(r,o);})};F.nativeEnum=function(t,e){let r=Object.values(t).filter(s=>typeof s=="string"||typeof s=="number"),n=r.some(s=>typeof s=="number")?r.filter(s=>typeof s=="number").map(s=>String(s)):r.filter(s=>typeof s=="string");return W((s,a)=>{O.enum(n,e??{})(s,a);})};F.char=function(t){return W((e,r)=>{O.string({...t,type:"char"})(e,r);})};F.varbinary=function(t){return W((e,r)=>{O({type:"varbinary",...t})(e,r);})};F.tinyint=function(t){return W((e,r)=>{O.integer({...t,type:"tinyint"})(e,r);})};F.smallint=function(t){return W((e,r)=>{O.integer({...t,type:"smallint"})(e,r);})};F.mediumint=function(t){return W((e,r)=>{O.integer({...t,type:"mediumint"})(e,r);})};F.encryption={symmetric(i){return W((t,e)=>{O.encryption.symmetric(i)(t,e);})},asymmetric(i){return W((t,e)=>{O.encryption.asymmetric(i)(t,e);})}};var Af=F;function xf(i,t){let{columns:e,indexes:r,uniques:o,checks:n,hooks:s,options:a}=t;class l extends Me{}l.table=i,a?.modelCaseConvention&&(l.modelCaseConvention=a.modelCaseConvention),a?.databaseCaseConvention&&(l.databaseCaseConvention=a.databaseCaseConvention),a?.softDeleteColumn&&(l.softDeleteColumn=a.softDeleteColumn),a?.softDeleteValue!==void 0&&(l.softDeleteValue=a.softDeleteValue);for(let[u,d]of Object.entries(e))d._apply(l.prototype,u);if(r)for(let u of r)$f(l,u);if(o)for(let u of o)Ef(l,u);if(n)for(let u of n)vf(l,u);return s&&(s.beforeFetch&&(l.beforeFetch=s.beforeFetch),s.afterFetch&&(l.afterFetch=s.afterFetch),s.beforeInsert&&(l.beforeInsert=s.beforeInsert),s.beforeInsertMany&&(l.beforeInsertMany=s.beforeInsertMany),s.beforeUpdate&&(l.beforeUpdate=s.beforeUpdate),s.beforeDelete&&(l.beforeDelete=s.beforeDelete)),l}function Df(i,t){let r=t({hasOne(o,n){return {_kind:"hasOne",_target:o,_foreignKey:n.foreignKey,_phantom:void 0}},hasMany(o,n){return {_kind:"hasMany",_target:o,_foreignKey:n.foreignKey,_phantom:void 0}},belongsTo(o,n){let{foreignKey:s,...a}=n;return {_kind:"belongsTo",_target:o,_foreignKey:s,_constraintOptions:a,_phantom:void 0}},manyToMany(o,n){let{through:s,leftForeignKey:a,rightForeignKey:l,...u}=n;return {_kind:"manyToMany",_target:o,_foreignKey:a,_throughModel:typeof s=="string"?s:(()=>s),_throughModelKeys:{leftForeignKey:a,rightForeignKey:l},_constraintOptions:u,_phantom:void 0}}});return {_source:i,_defs:r}}function If(i,t){for(let[e,r]of Object.entries(t||{})){if(!r)continue;let o=i[e];if(!o)throw new Error(`createSchema: relation key "${e}" does not match any model in the models record`);let n=r._defs;for(let[s,a]of Object.entries(n)){let l=a._target,u=a._foreignKey;switch(a._kind){case "hasOne":gl(()=>l,u)(o.prototype,s);break;case "hasMany":bl(()=>l,u)(o.prototype,s);break;case "belongsTo":hl(()=>l,u,a._constraintOptions)(o.prototype,s);break;case "manyToMany":{let d=a._throughModel,p=a._throughModelKeys;Tl(()=>l,d,p,a._constraintOptions)(o.prototype,s);break}}}}return i}function Pf(i,t){let{columns:e,statement:r,hooks:o,options:n}=t;class s extends Me{}s.table=i,s[fl]=r,n?.modelCaseConvention&&(s.modelCaseConvention=n.modelCaseConvention),n?.databaseCaseConvention&&(s.databaseCaseConvention=n.databaseCaseConvention);for(let[a,l]of Object.entries(e))l._apply(s.prototype,a);return o&&(o.beforeFetch&&(s.beforeFetch=o.beforeFetch),o.afterFetch&&(s.afterFetch=o.afterFetch)),s}function $f(i,t){Array.isArray(t)?Jr(t)(i):Jr(t.columns,t.name)(i);}function Ef(i,t){Array.isArray(t)?Hr(t)(i):Hr(t.columns,t.name)(i);}function vf(i,t){typeof t=="string"?zr(t)(i):zr(t.expression,t.name)(i);}var j=(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 S=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var x=class extends S{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 Se=class extends S{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var ie=class extends x{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 ye=class extends S{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 Yr=class{toSql(t){let e=t,r=new T(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:[]}}},Ml=new Yr;var Gr=class{toSql(t){let e=t,r=new T(this.model,"mssql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},_l=new Gr;var Zr=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`[${o}]`).join(", ")})`,bindings:[]}}},Ol=new Zr;var Xr=class{toSql(t){let e=t,r=new T(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 u=e.options.default;u===null?u="null":typeof u=="string"&&(u==="NULL"?u="null":u==="TRUE"||u==="FALSE"?u=u==="TRUE"?"1":"0":u=`'${u}'`),l+=`, add constraint DF_${e.column} default ${u} for [${e.column}]`;}return e.options.unique!==void 0&&e.options.unique&&(l+=`, add constraint UQ_${e.column} unique ([${e.column}])`),{sql:l,bindings:[]}}},Al=new Xr;var Ye=class extends S{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var eo=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 d=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${d.newName}'`,bindings:[]}}let n=new T(this.model,"mssql"),s=[],a=[];for(let d of e.children){let{sql:p,bindings:c}=n.parse([d]);s.push(p.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},xl=new eo;var to=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},Dl=new to;var ro=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},Il=new ro;var oo=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},Pl=new oo;var yt=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";case "oracledb":return "plsql";default:return "sql"}},kt=i=>{if(i==null)return "NULL";if(i instanceof Date)return `'${i.toISOString()}'`;let t=typeof i;return t==="boolean"?i?"TRUE":"FALSE":t==="number"&&Number.isFinite(i)||t==="bigint"?String(i):t==="string"?`'${i.replace(/'/g,"''")}'`:Array.isArray(i)||t==="object"&&Object.keys(i).length>0?`'${JSON.stringify(i).replace(/'/g,"''")}'`:String(i)},Ge=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,kt(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,kt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(o,kt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`:${r+1}(?!\\d)`,"g");e=e.replace(o,kt(t[r]));}return e},Ze=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:i==="oracledb"?t.errorNum===942:false:false,Xe=(i,t)=>{let e=i.getDbType(),r;try{r=format(t,{...i.inputDetails.queryFormatOptions,language:yt(e)});}catch{try{r=format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var El={info:0,warn:1,error:2};function Lt(i){return i?i===true?{level:"info",logQueries:true}:{level:i.level??"info",logQueries:i.logQueries??true,customLogger:i.customLogger}:null}function Kf(i,t="info"){let e=Lt(i);if(!e)return false;let r=e.level??"info";return El[t]>=El[r]}function kf(i){let t=Lt(i);return t?t.logQueries??true:false}var et={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function Lf(){let i=new Date,t=e=>e.toString().padStart(2,"0");return `${i.getFullYear()}-${t(i.getMonth()+1)}-${t(i.getDate())} ${t(i.getHours())}:${t(i.getMinutes())}:${t(i.getSeconds())}`}function no(i,t){let e=Lf(),r=i.toUpperCase();return i==="error"?`${et.error}[${r}] ${e}
|
|
1
|
+
import Me,{publicEncrypt,privateDecrypt,randomBytes}from'crypto';import Le from'dayjs';import Zp from'dayjs/plugin/customParseFormat.js';import Xp from'dayjs/plugin/timezone.js';import ef from'dayjs/plugin/utc.js';import {format}from'sql-formatter';import {highlight}from'sql-highlight';import {PassThrough,Readable}from'stream';import Wr from'fs';import mt from'path';import {fileURLToPath,pathToFileURL}from'url';import {createRequire}from'module';var Jp=Object.defineProperty;var al=i=>{throw TypeError(i)};var te=(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 ll=(i,t,e,r)=>{for(var o=void 0,n=i.length-1,s;n>=0;n--)(s=i[n])&&(o=(s(t,e,o))||o);return o&&Jp(t,e,o),o};var zp=(i,t,e)=>t.has(i)||al("Cannot "+e);var ul=(i,t,e)=>t.has(i)?al("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e);var dl=(i,t,e)=>(zp(i,t,"access private method"),e);var h=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}};function Yp(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 Gp(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function V(i,t){return t==="preserve"?i:t==="snake"?Yp(i):t==="camel"?Gp(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}Le.extend(ef);Le.extend(Xp);Le.extend(Zp);var se=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");let r=Le(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()}},ft=(i,t,e="UTC")=>{if(i===null)return null;if(i instanceof Date){if(isNaN(i.getTime()))throw new h("DateUtils::parseDate","INVALID_DATE_OBJECT");return i}try{let r=t?Le(i,t):Le(i);if(!r.isValid())throw new h("DateUtils::parseDate","INVALID_DATE_STRING");return e==="UTC"?r.utc().toDate():r.local().toDate()}catch(r){throw new h("DateUtils::parseDate","FAILED_TO_PARSE_DATE",r)}},He=(i=new Date)=>Le(i).utc().format("YYYY-MM-DD HH:mm:ss");var cl=(i,t)=>{try{let e=Me.createHash("sha256").update(i).digest(),r=Me.randomBytes(16),o=Me.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 h("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},ml=(i,t)=>{try{let e=Me.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.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),u=l.update(a,"hex","utf8");return u+=l.final("utf8"),u}catch(e){throw new h("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},pl=(i,t)=>{try{let e=Me.randomBytes(32),r=Me.randomBytes(16),o=Me.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new h("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},fl=(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=privateDecrypt(i,Buffer.from(o,"hex")),a=Me.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 h("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var Q=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);}}};Q.store=new WeakMap;var Vr="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ur=Vr.length,nf=10,sf=16,af=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%Ur;e=Vr.charAt(o)+e,i=(i-o)/Ur;}return e},lf=i=>{let t=randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=Vr.charAt(o%Ur);}return e},yl=()=>{let i=Math.floor(Date.now()/1e3),t=af(i,nf),e=lf(sf);return t+e};function Jr(i){return i.replace(/^[`"]|[`"]$/g,"")}function Hr(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 S(i){return typeof i=="function"?i():i}var L=(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]=L(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]=L(o,t);}return e};var Ne=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var It=class extends Ne{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var $t=class extends Ne{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Pt=class extends Ne{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Et=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 uf(i){return i.endsWith("ies")?i.slice(0,-3)+"y":i.endsWith("sses")||i.endsWith("shes")||i.endsWith("ches")||i.endsWith("xes")||i.endsWith("zes")?i.slice(0,-2):i.endsWith("s")&&!i.endsWith("ss")?i.slice(0,-1):i}var vt=Symbol("columns"),ze=Symbol("primaryKey"),fe=Symbol("relations"),Bt=Symbol("indexes"),Kt=Symbol("uniques"),Qt=Symbol("checks"),De=i=>`${uf(i)}_id`,kt=(i,t)=>`idx_${i}_${t}`,ue=(i,t)=>`uq_${i}_${t}`,z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,ye=(i,t)=>`pk_${i}_${t}`,hl=(i,t)=>{let e=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_|_$/g,"").toLowerCase();return `chk_${i}_${e}`.substring(0,63)};function zr(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=Q.getMetadata(Bt,e.prototype)||[];o.push({columns:r,name:t??kt(e.table,r.join("_"))}),Q.defineMetadata(Bt,o,e.prototype);}}function Yr(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=Q.getMetadata(Kt,e.prototype)||[];o.push({columns:r,name:t??ue(e.table,r.join("_"))}),Q.defineMetadata(Kt,o,e.prototype);}}function Gr(i,t){return e=>{let r=Q.getMetadata(Qt,e.prototype)||[];r.push({expression:i,name:t??hl(e.table,i)}),Q.defineMetadata(Qt,r,e.prototype);}}var gl=Symbol("viewStatement");function O(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(Q.getMetadata(ze,e))throw new h("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");Q.defineMetadata(ze,r,e),Q.defineMetadata(ze,r,e.constructor);}let n=i.databaseName??V(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??ye(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=Q.getMetadata(vt,e)||[];a.push(s),Q.defineMetadata(vt,a,e);}}O.primary=cf;O.date=_f;O.datetime=Of;O.timestamp=Af;O.time=xf;O.boolean=Mf;O.json=Df;O.uuid=hf;O.ulid=gf;O.integer=pf;O.bigInteger=wf;O.float=mf;O.decimal=Nf;O.increment=ff;O.bigIncrement=yf;O.string=bf;O.text=Tf;O.binary=Sf;O.enum=qf;O.encryption={symmetric:Cf,asymmetric:Rf};function cf(i={}){return O({...i,primaryKey:true})}function mf(i={}){return O({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?Number.parseInt(t):Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function pf(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)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function ff(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)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function yf(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)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function hf(i={}){return O({type:"uuid",...i,prepare:t=>t||Me.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function gf(i={}){return O({type:"ulid",...i,prepare:t=>t||yl(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function bf(i={}){return O({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Tf(i={}){return O({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function wf(i={}){return O({type:"bigint",...i,serialize:t=>{if(t!==void 0){if(t===null)return null;if(typeof t=="number")return t;if(typeof t=="string")return Number.parseInt(t);if(typeof t=="bigint")return Number(t)}},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function Nf(i={}){return O({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function Sf(i={}){return O({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function qf(i,t={}){return O({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Cf(i){return O({...i,prepare:t=>t&&cl(i.key,t),serialize:t=>t&&ml(i.key,t)})}function Rf(i){return O({...i,prepare:t=>t&&pl(i.publicKey,t),serialize:t=>t&&fl(i.privateKey,t)})}function Mf(i={}){return O({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function _f(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=u=>u?e?se(new Date,"DATE_ONLY",t):typeof u=="string"?u:se(u,"DATE_ONLY",t):r?se(new Date,"DATE_ONLY",t):null,l=u=>{if(u!==void 0)return u===null?null:ft(u,void 0,t)};return O({type:"date",...s,autoUpdate:e,prepare:u=>{let d=a(u);return o?o(d):d},serialize:u=>{let d=l(u);return n?n(d):d},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...s.openApi||{}}})}function Of(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",u=e??t!==void 0,d=c=>c?r?se(new Date,"ISO",l):typeof c=="string"?c:se(c,"ISO",l):o?se(new Date,"ISO",l):null,p=c=>{if(c!==void 0)return c===null?null:ft(c,void 0,l)};return O({type:"datetime",...a,withTimezone:u,autoUpdate:r,prepare:c=>{let m=d(c);return n?n(m):m},serialize:c=>{let m=p(c);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...a.openApi||{}}})}function Af(i={}){let{timezone:t,withTimezone:e,autoUpdate:r=false,autoCreate:o=false,prepare:n,serialize:s,...a}=i,l=t??"UTC",u=e??t!==void 0,d=c=>c?r?se(new Date,"TIMESTAMP",l):typeof c=="string"?c:se(c,"TIMESTAMP",l):o?se(new Date,"TIMESTAMP",l):null,p=c=>{if(c!==void 0)return c===null?null:ft(c,void 0,l)};return O({type:"timestamp",...a,withTimezone:u,autoUpdate:r,prepare:c=>{let m=d(c);return n?n(m):m},serialize:c=>{let m=p(c);return s?s(m):m},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...a.openApi||{}}})}function xf(i={}){let{timezone:t="UTC",autoUpdate:e=false,autoCreate:r=false,prepare:o,serialize:n,...s}=i,a=u=>u?e?se(new Date,"TIME_ONLY",t):typeof u=="string"?u:se(u,"TIME_ONLY",t):r?se(new Date,"TIME_ONLY",t):null,l=u=>{if(u!==void 0)return u===null?null:ft(u,void 0,t)};return O({type:"time",...s,autoUpdate:e,prepare:u=>{let d=a(u);return o?o(d):d},serialize:u=>{let d=l(u);return n?n(d):d},openApi:{type:"string",format:"time",description:"HH:mm:ss",...s.openApi||{}}})}function Df(i={}){return O({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function bl(i){try{return Q.getMetadata(vt,i.prototype)||[]}catch{return []}}function Tl(i,t,e){return((r,o)=>{let n=()=>De(i().table),s=()=>{let u=r.constructor.table,d=t||n();return z(u,d,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=Q.getMetadata(fe,r)||[];l.push(a),Q.defineMetadata(fe,l,r);})}function wl(i,t){return((e,r)=>{let o=()=>De(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=Q.getMetadata(fe,e)||[];s.push(n),Q.defineMetadata(fe,s,e);})}function Nl(i,t){return((e,r)=>{let o=()=>De(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=Q.getMetadata(fe,e)||[];s.push(n),Q.defineMetadata(fe,s,e);})}function Sl(i,t,e,r){return((o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",u=typeof t=="string"?t:()=>t().table,d=o.constructor.table,p=()=>De(d),c=()=>De(i().table),m=()=>z(S(u),s?String(s):p()),g={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??m,foreignKey:s?String(s):p,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:d,throughModel:u,leftForeignKey:s?String(s):p,rightForeignKey:a?String(a):c,wasModelProvided:l}},f=Q.getMetadata(fe,o)||[];f.push(g),Q.defineMetadata(fe,f,o);})}function ql(i){return Q.getMetadata(fe,i.prototype)||[]}function Cl(i){return (Q.getMetadata(fe,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=S(s),l=o();switch(r){case "belongsTo":return new It(l,n,a);case "hasOne":return new Pt(l,n,a);case "hasMany":return new $t(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new h("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=o();return new Et(u,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:S(e.manyToManyOptions.throughModel),leftForeignKey:S(e.manyToManyOptions.leftForeignKey),rightForeignKey:S(e.manyToManyOptions.rightForeignKey)});default:throw new h("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Rl(i){return Q.getMetadata(ze,i)||Q.getMetadata(ze,i.prototype)}function Ml(i){return Q.getMetadata(Bt,i.prototype)||[]}function _l(i){return Q.getMetadata(Kt,i.prototype)||[]}function Ol(i){return Q.getMetadata(Qt,i.prototype)||[]}var Ie=class{};Ie.modelCaseConvention="camel",Ie.databaseCaseConvention="snake";var de=class{};de.columns=new WeakMap,de.byName=new WeakMap,de.byDatabaseName=new WeakMap;var _e=class extends Ie{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");if(t&&"value"in t)return t.value;throw new Error(`Table name not set for model "${this.name}". Use defineModel() to create models.`)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Rl(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=de.columns.get(this);return t||(t=bl(this),de.columns.set(this,t)),t}static getColumnsByName(){let t=de.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),de.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=de.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),de.byDatabaseName.set(this,t)),t}static getRelations(){return ql(this)}static getIndexes(){return Ml(this)}static getUniques(){return _l(this)}static getChecks(){return Ol(this)}};_e.softDeleteColumn="deletedAt",_e.softDeleteValue=He();function W(i){return {_phantom:void 0,_apply:i}}function F(i={}){return W((t,e)=>{O(i)(t,e);})}F.primary=function(t={}){return W((e,r)=>{O.primary(t)(e,r);})};F.string=function(t){return W((e,r)=>{O.string(t??{})(e,r);})};F.text=function(t){return W((e,r)=>{O.text(t??{})(e,r);})};F.integer=function(t){return W((e,r)=>{O.integer(t??{})(e,r);})};F.bigInteger=function(t){return W((e,r)=>{O.bigInteger(t??{})(e,r);})};F.float=function(t){return W((e,r)=>{O.float(t??{})(e,r);})};F.decimal=function(t){return W((e,r)=>{O.decimal(t??{})(e,r);})};F.increment=function(t={}){return W((e,r)=>{O.increment(t)(e,r);})};F.bigIncrement=function(t={}){return W((e,r)=>{O.bigIncrement(t)(e,r);})};F.boolean=function(t){return W((e,r)=>{O.boolean(t??{})(e,r);})};F.date=function(t){return W((e,r)=>{O.date(t??{})(e,r);})};F.datetime=function(t){return W((e,r)=>{O.datetime(t??{})(e,r);})};F.timestamp=function(t){return W((e,r)=>{O.timestamp(t??{})(e,r);})};F.time=function(t){return W((e,r)=>{O.time(t??{})(e,r);})};F.json=function(t){return W((e,r)=>{O.json({type:"json",...t??{}})(e,r);})};F.jsonb=function(t){return W((e,r)=>{O.json(t??{})(e,r);})};F.uuid=function(t){return W((e,r)=>{O.uuid(t??{})(e,r);})};F.ulid=function(t){return W((e,r)=>{O.ulid(t??{})(e,r);})};F.binary=function(t){return W((e,r)=>{O.binary(t??{})(e,r);})};F.enum=function(t,e){return W((r,o)=>{O.enum(t,e??{})(r,o);})};F.nativeEnum=function(t,e){let r=Object.values(t).filter(s=>typeof s=="string"||typeof s=="number"),n=r.some(s=>typeof s=="number")?r.filter(s=>typeof s=="number").map(s=>String(s)):r.filter(s=>typeof s=="string");return W((s,a)=>{O.enum(n,e??{})(s,a);})};F.char=function(t){return W((e,r)=>{O.string({...t,type:"char"})(e,r);})};F.varbinary=function(t){return W((e,r)=>{O({type:"varbinary",...t})(e,r);})};F.tinyint=function(t){return W((e,r)=>{O.integer({...t,type:"tinyint"})(e,r);})};F.smallint=function(t){return W((e,r)=>{O.integer({...t,type:"smallint"})(e,r);})};F.mediumint=function(t){return W((e,r)=>{O.integer({...t,type:"mediumint"})(e,r);})};F.encryption={symmetric(i){return W((t,e)=>{O.encryption.symmetric(i)(t,e);})},asymmetric(i){return W((t,e)=>{O.encryption.asymmetric(i)(t,e);})}};var If=F;function $f(i,t){let{columns:e,indexes:r,uniques:o,checks:n,hooks:s,options:a}=t;class l extends _e{}l.table=i,a?.modelCaseConvention&&(l.modelCaseConvention=a.modelCaseConvention),a?.databaseCaseConvention&&(l.databaseCaseConvention=a.databaseCaseConvention),a?.softDeleteColumn&&(l.softDeleteColumn=a.softDeleteColumn),a?.softDeleteValue!==void 0&&(l.softDeleteValue=a.softDeleteValue);for(let[u,d]of Object.entries(e))d._apply(l.prototype,u);if(r)for(let u of r)Bf(l,u);if(o)for(let u of o)Kf(l,u);if(n)for(let u of n)Qf(l,u);return s&&(s.beforeFetch&&(l.beforeFetch=s.beforeFetch),s.afterFetch&&(l.afterFetch=s.afterFetch),s.beforeInsert&&(l.beforeInsert=s.beforeInsert),s.beforeInsertMany&&(l.beforeInsertMany=s.beforeInsertMany),s.beforeUpdate&&(l.beforeUpdate=s.beforeUpdate),s.beforeDelete&&(l.beforeDelete=s.beforeDelete)),l}function Pf(i,t){let r=t({hasOne(o,n){return {_kind:"hasOne",_target:o,_foreignKey:n.foreignKey,_phantom:void 0}},hasMany(o,n){return {_kind:"hasMany",_target:o,_foreignKey:n.foreignKey,_phantom:void 0}},belongsTo(o,n){let{foreignKey:s,...a}=n;return {_kind:"belongsTo",_target:o,_foreignKey:s,_constraintOptions:a,_phantom:void 0}},manyToMany(o,n){let{through:s,leftForeignKey:a,rightForeignKey:l,...u}=n;return {_kind:"manyToMany",_target:o,_foreignKey:a,_throughModel:typeof s=="string"?s:(()=>s),_throughModelKeys:{leftForeignKey:a,rightForeignKey:l},_constraintOptions:u,_phantom:void 0}}});return {_source:i,_defs:r}}function Ef(i,t){for(let[e,r]of Object.entries(t||{})){if(!r)continue;let o=i[e];if(!o)throw new Error(`createSchema: relation key "${e}" does not match any model in the models record`);let n=r._defs;for(let[s,a]of Object.entries(n)){let l=a._target,u=a._foreignKey;switch(a._kind){case "hasOne":wl(()=>l,u)(o.prototype,s);break;case "hasMany":Nl(()=>l,u)(o.prototype,s);break;case "belongsTo":Tl(()=>l,u,a._constraintOptions)(o.prototype,s);break;case "manyToMany":{let d=a._throughModel,p=a._throughModelKeys;Sl(()=>l,d,p,a._constraintOptions)(o.prototype,s);break}}}}return i}function vf(i,t){let{columns:e,statement:r,hooks:o,options:n}=t;class s extends _e{}s.table=i,s[gl]=r,n?.modelCaseConvention&&(s.modelCaseConvention=n.modelCaseConvention),n?.databaseCaseConvention&&(s.databaseCaseConvention=n.databaseCaseConvention);for(let[a,l]of Object.entries(e))l._apply(s.prototype,a);return o&&(o.beforeFetch&&(s.beforeFetch=o.beforeFetch),o.afterFetch&&(s.afterFetch=o.afterFetch)),s}function Bf(i,t){Array.isArray(t)?zr(t)(i):zr(t.columns,t.name)(i);}function Kf(i,t){Array.isArray(t)?Yr(t)(i):Yr(t.columns,t.name)(i);}function Qf(i,t){typeof t=="string"?Gr(t)(i):Gr(t.expression,t.name)(i);}var j=(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 N=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var x=class extends N{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 qe=class extends N{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var ie=class extends x{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 he=class extends N{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 Zr=class{toSql(t){let e=t,r=new T(this.model,"mssql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add ${o}`,bindings:[]}}},Al=new Zr;var Xr=class{toSql(t){let e=t,r=new T(this.model,"mssql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},xl=new Xr;var eo=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`[${o}]`).join(", ")})`,bindings:[]}}},Dl=new eo;var to=class{toSql(t){let e=t,r=new T(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 u=e.options.default;u===null?u="null":typeof u=="string"&&(u==="NULL"?u="null":u==="TRUE"||u==="FALSE"?u=u==="TRUE"?"1":"0":u=`'${u}'`),l+=`, add constraint DF_${e.column} default ${u} for [${e.column}]`;}return e.options.unique!==void 0&&e.options.unique&&(l+=`, add constraint UQ_${e.column} unique ([${e.column}])`),{sql:l,bindings:[]}}},Il=new to;var Ye=class extends N{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var ro=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 d=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${d.newName}'`,bindings:[]}}let n=new T(this.model,"mssql"),s=[],a=[];for(let d of e.children){let{sql:p,bindings:c}=n.parse([d]);s.push(p.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},$l=new ro;var oo=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},Pl=new oo;var no=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},El=new no;var so=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},vl=new so;var yt=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"}},Lt=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)},Ge=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,Lt(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,Lt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(o,Lt(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`:${r+1}(?!\\d)`,"g");e=e.replace(o,Lt(t[r]));}return e},Ze=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:i==="oracledb"?t.errorNum===942:false:false,Xe=(i,t)=>{let e=i.getDbType(),r;try{r=format(t,{...i.inputDetails.queryFormatOptions,language:yt(e)});}catch{try{r=format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var Kl={info:0,warn:1,error:2};function Wt(i){return i?i===true?{level:"info",logQueries:true}:{level:i.level??"info",logQueries:i.logQueries??true,customLogger:i.customLogger}:null}function Wf(i,t="info"){let e=Wt(i);if(!e)return false;let r=e.level??"info";return Kl[t]>=Kl[r]}function jf(i){let t=Wt(i);return t?t.logQueries??true:false}var et={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function Ff(){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 io(i,t){let e=Ff(),r=i.toUpperCase();return i==="error"?`${et.error}[${r}] ${e}
|
|
2
2
|
${t}${et.reset}
|
|
3
3
|
`:i==="warn"?`${et.warn}[${r}] ${e}
|
|
4
4
|
${t}${et.reset}
|
|
@@ -6,12 +6,12 @@ ${t}${et.reset}
|
|
|
6
6
|
${t}${et.reset}
|
|
7
7
|
`:`[${r}] ${e}
|
|
8
8
|
${t}
|
|
9
|
-
`}var tt=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);}};tt.loggerInstance={info(t){console.log(no("info",t));},error(t){console.error(no("error",t));},warn(t){console.warn(no("warn",t));}};function Wf(i){return i.map(t=>typeof t=="object"?JSON.stringify(t):typeof t=="string"?`'${t}'`:typeof t=="number"?t:typeof t=="boolean"?t?"true":"false":t).join(", ")}function oe(i,t,e,r,o){if(!kf(t))return;let n=i;if(r||o)try{n=format(i,{...r,language:r?.language??(o?yt(o):void 0)});}catch{n=i;}let a=`${highlight(n,{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"}})} [${Wf(e||[])}]`;tt.loggerInstance.info(a);}function vl(i,t,e=false){Kf(e,t)&&tt.loggerInstance[t](i);}var _=tt;var so=class{toSql(t){let e=t;return _.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},Bl=new so;var io=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},Ql=new io;var ao=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},Kl=new ao;var lo=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},kl=new lo;var P=class extends S{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 uo=class{toSql(t){let e=t,r;return e.defaultValue instanceof P?r=e.defaultValue.rawValue:e.defaultValue==="NULL"||e.defaultValue===null?r="null":e.defaultValue==="TRUE"?r="1":e.defaultValue==="FALSE"?r="0":typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="1"&&e.defaultValue!=="0"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`add constraint DF_${e.column} default ${r} for [${e.column}]`,bindings:[]}}},Ll=new uo;var co=class{toSql(t){let e=t;return _.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},Wl=new co;var mo=class{toSql(t){return {sql:"",bindings:[]}}},jl=new mo;var po=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 a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar(${a})`,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 a=e.precision??10,l=e.scale??0;return {sql:`${o} decimal(${a}, ${l})`,bindings:[]}}if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${a}`,bindings:[]}}if(n==="datetime"||n==="timestamp"){let a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${o} datetime2${a}`;return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,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 a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} varchar(255) check (${o} in (${a}))`,bindings:[]}}return {sql:`${o} varchar(255)`,bindings:[]}}if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} int identity(1,1)`,bindings:[]}:{sql:`${o} int`,bindings:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} geometry`,bindings:[]};if(n==="linestring")return {sql:`${o} geometry`,bindings:[]};if(n==="polygon")return {sql:`${o} geometry`,bindings:[]};if(n==="multipoint")return {sql:`${o} geometry`,bindings:[]};let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},Fl=new po;var fo=class{toSql(t){return {sql:"",bindings:[]}}},Ul=new fo;var yo=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 P?{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(u=>r.formatStringColumn("mssql",N(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("mssql",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("mssql",N(u))).join(", "),l=`${e.constraintName?`constraint [${e.constraintName}] `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint [${e.constraintName}] `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Vl=new yo;var ho=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 T(this.model,"mssql"),s=[],a=[];for(let g of e.children){let{sql:f,bindings:b}=n.parse([g]);if(g.folder==="constraint"){let w=s.pop()??"",q=f;if(/not null/i.test(q)||/null/i.test(q)||/default/i.test(q)){let M=`${w} ${q}`.trim();M=M.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(M),a.push(...b);continue}s.push(w),s.push(q),a.push(...b);continue}s.push(f),a.push(...b);}for(let g of e.namedConstraints){let{sql:f,bindings:b}=n.parse([g]);s.push(f),a.push(...b);}let l=s.join(", "),u=[];e.dataCompression&&u.push(`DATA_COMPRESSION = ${e.dataCompression}`);let d=e.onFilegroup?` ON [${e.onFilegroup}]`:"",p=e.textImageOn?` TEXTIMAGE_ON [${e.textImageOn}]`:"",c=u.length>0?` WITH (${u.join(", ")})`:"";return {sql:`${o} (${l})${c}${d}${p}`,bindings:a}}},Jl=new ho;var go=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode.table=="string")return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),n=r.getFromForWriteOperations("mssql",e.fromNode);if(e.returning&&e.returning.length){let s=e.returning.map(a=>`deleted.${r.formatStringColumn("mssql",a)}`).join(", ");n+=` output ${s}`;}return {sql:n,bindings:[]}}},Hl=new go;var bo=class{toSql(t){return {sql:"",bindings:[]}}},zl=new bo;var To=class{toSql(t){return _.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},Yl=new To;var wo=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Gl=new wo;var So=class{toSql(t){return {sql:`-- MSSQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Zl=new So;var No=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 T(this.model,"mssql").parse(r),s=e.alias&&e.alias.length?` as [${e.alias}]`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Xl=new No;var qo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},eu=new qo;var Co=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 S)&&!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}}},tu=new Co;var Ro=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:[]}}},ru=new Ro;var Mo=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},ou=new Mo;var _o=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=[],u=[],d=e.currParamIndex;for(let c of e.records){let m=s.map(f=>c[f]),g=[];for(let f of m)f instanceof P?g.push(f.rawValue):(l.push(f),g.push(`@${d++}`));u.push(`(${g.join(", ")})`);}let p=`${o} (${a}) values ${u.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(m=>`inserted.${r.formatStringColumn("mssql",m)}`).join(", ");p=p.replace(") values",`) output ${c} values`);}else {let c=this.getOutputColumns(s,r);p=p.replace(") values",`) output ${c} values`);}return {sql:p,bindings:l}}getOutputColumns(t,e){let r=[...t],o=this.model.primaryKey;return o&&!t.includes(o)&&r.push(o),r.map(n=>`inserted.${e.formatStringColumn("mssql",n)}`).join(", ")}},nu=new _o;var Oo=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),u=`${r.formatStringTable("mssql",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"mssql");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},su=new Oo;var Ao=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},iu=new Ao;var xo=class{toSql(t){return {sql:"",bindings:[]}}},au=new xo;var Do=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},lu=new Do;var Io=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(_.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:[]})}},uu=new Io;var Po=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:[]}}},du=new Po;var $o=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},cu=new $o;var Eo=class{toSql(t){return {sql:`SELECT
|
|
9
|
+
`}var tt=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);}};tt.loggerInstance={info(t){console.log(io("info",t));},error(t){console.error(io("error",t));},warn(t){console.warn(io("warn",t));}};function Uf(i){return i.map(t=>typeof t=="object"?JSON.stringify(t):typeof t=="string"?`'${t}'`:typeof t=="number"?t:typeof t=="boolean"?t?"true":"false":t).join(", ")}function oe(i,t,e,r,o){if(!jf(t))return;let n=i;if(r||o)try{n=format(i,{...r,language:r?.language??(o?yt(o):void 0)});}catch{n=i;}let a=`${highlight(n,{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"}})} [${Uf(e||[])}]`;tt.loggerInstance.info(a);}function Ql(i,t,e=false){Wf(e,t)&&tt.loggerInstance[t](i);}var _=tt;var ao=class{toSql(t){let e=t;return _.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},kl=new ao;var lo=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},Ll=new lo;var uo=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},Wl=new uo;var co=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},jl=new co;var $=class extends N{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 mo=class{toSql(t){let e=t,r;return e.defaultValue instanceof $?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:[]}}},Fl=new mo;var po=class{toSql(t){let e=t;return _.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 po;var fo=class{toSql(t){return {sql:"",bindings:[]}}},Vl=new fo;var yo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mssql",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar(${a})`,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 a=e.precision??10,l=e.scale??0;return {sql:`${o} decimal(${a}, ${l})`,bindings:[]}}if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${a}`,bindings:[]}}if(n==="datetime"||n==="timestamp"){let a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${o} datetime2${a}`;return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,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 a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} varchar(255) check (${o} in (${a}))`,bindings:[]}}return {sql:`${o} varchar(255)`,bindings:[]}}if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} int identity(1,1)`,bindings:[]}:{sql:`${o} int`,bindings:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} geometry`,bindings:[]};if(n==="linestring")return {sql:`${o} geometry`,bindings:[]};if(n==="polygon")return {sql:`${o} geometry`,bindings:[]};if(n==="multipoint")return {sql:`${o} geometry`,bindings:[]};let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},Jl=new yo;var ho=class{toSql(t){return {sql:"",bindings:[]}}},Hl=new ho;var go=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",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint [${e.constraintName}] `:"",s=o.map(a=>r.formatStringColumn("mssql",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof $?{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(u=>r.formatStringColumn("mssql",S(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("mssql",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("mssql",S(u))).join(", "),l=`${e.constraintName?`constraint [${e.constraintName}] `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint [${e.constraintName}] `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},zl=new go;var bo=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 T(this.model,"mssql"),s=[],a=[];for(let g of e.children){let{sql:f,bindings:b}=n.parse([g]);if(g.folder==="constraint"){let w=s.pop()??"",q=f;if(/not null/i.test(q)||/null/i.test(q)||/default/i.test(q)){let M=`${w} ${q}`.trim();M=M.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(M),a.push(...b);continue}s.push(w),s.push(q),a.push(...b);continue}s.push(f),a.push(...b);}for(let g of e.namedConstraints){let{sql:f,bindings:b}=n.parse([g]);s.push(f),a.push(...b);}let l=s.join(", "),u=[];e.dataCompression&&u.push(`DATA_COMPRESSION = ${e.dataCompression}`);let d=e.onFilegroup?` ON [${e.onFilegroup}]`:"",p=e.textImageOn?` TEXTIMAGE_ON [${e.textImageOn}]`:"",c=u.length>0?` WITH (${u.join(", ")})`:"";return {sql:`${o} (${l})${c}${d}${p}`,bindings:a}}},Yl=new bo;var To=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode.table=="string")return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),n=r.getFromForWriteOperations("mssql",e.fromNode);if(e.returning&&e.returning.length){let s=e.returning.map(a=>`deleted.${r.formatStringColumn("mssql",a)}`).join(", ");n+=` output ${s}`;}return {sql:n,bindings:[]}}},Gl=new To;var wo=class{toSql(t){return {sql:"",bindings:[]}}},Zl=new wo;var No=class{toSql(t){return _.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},Xl=new No;var So=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},eu=new So;var qo=class{toSql(t){return {sql:`-- MSSQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},tu=new qo;var Co=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 T(this.model,"mssql").parse(r),s=e.alias&&e.alias.length?` as [${e.alias}]`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},ru=new Co;var Ro=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},ou=new Ro;var Mo=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 N)&&!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}}},nu=new Mo;var _o=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:[]}}},su=new _o;var Oo=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},iu=new Oo;var Ao=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),o=r.getFromForWriteOperations("mssql",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n).filter(c=>n[c]!==void 0);if(!s.length)return {sql:o,bindings:[]};let a=s.map(c=>r.formatStringColumn("mssql",c)).join(", "),l=[],u=[],d=e.currParamIndex;for(let c of e.records){let m=s.map(f=>c[f]),g=[];for(let f of m)f instanceof $?g.push(f.rawValue):(l.push(f),g.push(`@${d++}`));u.push(`(${g.join(", ")})`);}let p=`${o} (${a}) values ${u.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(m=>`inserted.${r.formatStringColumn("mssql",m)}`).join(", ");p=p.replace(") values",`) output ${c} values`);}else {let c=this.getOutputColumns(s,r);p=p.replace(") values",`) output ${c} values`);}return {sql:p,bindings:l}}getOutputColumns(t,e){let r=[...t],o=this.model.primaryKey;return o&&!t.includes(o)&&r.push(o),r.map(n=>`inserted.${e.formatStringColumn("mssql",n)}`).join(", ")}},au=new Ao;var xo=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),u=`${r.formatStringTable("mssql",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"mssql");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},lu=new xo;var Do=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},uu=new Do;var Io=class{toSql(t){return {sql:"",bindings:[]}}},du=new Io;var $o=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},cu=new $o;var Po=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(_.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:[]})}},mu=new Po;var Eo=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:[]}}},pu=new Eo;var vo=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},fu=new vo;var Bo=class{toSql(t){return {sql:`SELECT
|
|
10
10
|
cc.name AS name,
|
|
11
11
|
cc.definition AS expression
|
|
12
12
|
FROM sys.check_constraints cc
|
|
13
13
|
JOIN sys.tables t ON cc.parent_object_id = t.object_id
|
|
14
|
-
WHERE t.name = '${t.table}'`,bindings:[]}}},
|
|
14
|
+
WHERE t.name = '${t.table}'`,bindings:[]}}},yu=new Bo;var Ko=class{toSql(t){return {sql:`SELECT
|
|
15
15
|
fk.name as name,
|
|
16
16
|
c.name as column_name,
|
|
17
17
|
rt.name as referenced_table,
|
|
@@ -23,7 +23,7 @@ INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_i
|
|
|
23
23
|
INNER JOIN sys.columns c ON fkc.parent_object_id = c.object_id AND fkc.parent_column_id = c.column_id
|
|
24
24
|
INNER JOIN sys.tables rt ON fkc.referenced_object_id = rt.object_id
|
|
25
25
|
INNER JOIN sys.columns rc ON fkc.referenced_object_id = rc.object_id AND fkc.referenced_column_id = rc.column_id
|
|
26
|
-
WHERE fk.parent_object_id = OBJECT_ID('${t.table}')`,bindings:[]}}},
|
|
26
|
+
WHERE fk.parent_object_id = OBJECT_ID('${t.table}')`,bindings:[]}}},hu=new Ko;var Qo=class{toSql(t){return {sql:`SELECT
|
|
27
27
|
i.name as index_name,
|
|
28
28
|
c.name as column_name,
|
|
29
29
|
i.is_unique as is_unique
|
|
@@ -32,7 +32,7 @@ INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = i
|
|
|
32
32
|
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
33
33
|
WHERE i.object_id = OBJECT_ID('${t.table}')
|
|
34
34
|
AND i.is_primary_key = 0
|
|
35
|
-
AND i.type > 0`,bindings:[]}}},
|
|
35
|
+
AND i.type > 0`,bindings:[]}}},gu=new Qo;var ko=class{toSql(t){return {sql:`SELECT
|
|
36
36
|
tc.CONSTRAINT_NAME as name,
|
|
37
37
|
kcu.COLUMN_NAME as column_name
|
|
38
38
|
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
|
|
@@ -40,7 +40,7 @@ JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
|
|
|
40
40
|
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
|
|
41
41
|
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
|
|
42
42
|
AND tc.TABLE_NAME = '${t.table}'
|
|
43
|
-
ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},
|
|
43
|
+
ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},bu=new ko;var Lo=class{toSql(t){return {sql:`SELECT
|
|
44
44
|
c.COLUMN_NAME as column_name,
|
|
45
45
|
c.DATA_TYPE as data_type,
|
|
46
46
|
c.IS_NULLABLE as is_nullable,
|
|
@@ -50,7 +50,7 @@ ORDER BY kcu.ORDINAL_POSITION`,bindings:[]}}},yu=new Qo;var Ko=class{toSql(t){re
|
|
|
50
50
|
c.NUMERIC_SCALE as numeric_scale
|
|
51
51
|
FROM INFORMATION_SCHEMA.COLUMNS c
|
|
52
52
|
WHERE c.TABLE_NAME = '${t.table}'
|
|
53
|
-
ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},hu=new Ko;var ko=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 T(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 T(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 T(this.model,"mssql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as [${t}]`:""}},gu=new ko;var ce=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 Lo=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=ce.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}},bu=new Lo;var Wo=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:[]}}},Tu=new Wo;var jo=class{toSql(t){let e=t,r=new T(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}}},wu=new jo;var Fo=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((u,d)=>{let p=e.currParamIndex+d-n,c=e.values[d];return c instanceof P?(n++,`${r.formatStringColumn("mssql",u)} = ${c.rawValue}`):(s.push(c),`${r.formatStringColumn("mssql",u)} = @${p}`)}).join(", "),l=`${o} set ${a}`;if(e.returning&&e.returning.length){let u=e.returning.map(d=>`inserted.${r.formatStringColumn("mssql",d)}`).join(", ");l+=` output ${u}`;}return {sql:l,bindings:s}}},Su=new Fo;var Uo=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 d=`@${o} AND @${o+1}`,p=`${a} between ${d}`;return e.isNegated&&(p=`not (${p})`),{sql:p.trim(),bindings:r}}let l=r.map((d,p)=>`@${o+p}`).join(", "),u=`${a} ${e.operator} (${l})`;return e.isNegated&&(u=`not (${u})`),{sql:u.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}},Nu=new Uo;var Vo=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new T(this.model,"mssql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},qu=new Vo;var Jo=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}}},Cu=new Jo;var Ho=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"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 T(this.model,"mssql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Ru=new Ho;var zo=class{toSql(t){let e=t,r=new T(this.model,"mssql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return e.clause==="materialized"&&_.warn("MSSQL does not support MATERIALIZED CTEs. The clause will be ignored."),{sql:`[${e.alias}] as (${n.sql})`,bindings:n.bindings}}},Mu=new zo;var Yo=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},_u=new Yo;var Go=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Ou=new Go;var Zo=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},Au=new Zo;var Xo=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify column \`${e.column}\` ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?"":" not null";a+=l;}if(!e.options.dropDefault){if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=` default ${l}`;}}return e.options.collate&&(a+=` COLLATE ${e.options.collate}`),e.options.unique!==void 0&&e.options.unique&&(a+=" unique"),{sql:a,bindings:[]}}},xu=new Xo;var en=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 T(this.model,"mysql"),s=[],a=[];for(let c of e.children){let{sql:m,bindings:g}=n.parse([c]);if(c.file==="add_column")s.push(m);else if(c.file==="add_constraint"||c.folder==="constraint"){let f=s[s.length-1]??"",b=/^\s*add\s+column\b/i.test(f),w=/^\s*add\s+constraint\b/i.test(m);if(b&&!w){let q=m.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${f} ${q}`;}else {let q=/^\s*add\b/i.test(m)?m:`add ${m}`;s.push(q);}}else c.file==="set_default"||c.file==="drop_default"||c.file==="set_not_null"||c.file,s.push(m);a.push(...g);}let l=s.join(", "),u=e.ifExists?"if exists ":"";return {sql:/^\s*drop\s+index\b/i.test(l)?l:`${u}${o} ${l}`,bindings:a}}},Du=new en;var tn=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},Iu=new tn;var rn=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},Pu=new rn;var on=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},$u=new on;var nn=class{toSql(t){return {sql:"",bindings:[]}}},Eu=new nn;var sn=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},vu=new sn;var an=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},Bu=new an;var ln=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},Qu=new ln;var un=class{toSql(t){let e=t,r;return e.defaultValue instanceof P?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:[]}}},Ku=new un;var dn=class{toSql(t){return {sql:"",bindings:[]}}},ku=new dn;var cn=class{toSql(t){let e=t,r=[];return e.engine&&r.push(`ENGINE=${e.engine}`),e.charset&&r.push(`CHARSET=${e.charset}`),e.collate&&r.push(`COLLATE=${e.collate}`),{sql:r.join(" "),bindings:[]}}},Lu=new cn;var mn=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(),s,a=false,l=false;if(n==="char"){let u=e.length??1;s=`${o} char(${u})`;}else if(n==="varchar"){let u=e.length??255;s=`${o} varchar(${u})`;}else if(n==="uuid")s=`${o} varchar(36)`;else if(n==="ulid")s=`${o} varchar(26)`;else if(n==="longtext"||n==="mediumtext"||n==="tinytext"||n==="text")s=`${o} ${n}`;else if(n==="integer"||n==="int")a=true,l=!!e.autoIncrement,s=`${o} int`;else if(n==="tinyint")a=true,s=`${o} tinyint`;else if(n==="smallint")a=true,s=`${o} smallint`;else if(n==="mediumint")a=true,s=`${o} mediumint`;else if(n==="bigint")a=true,l=!!e.autoIncrement,s=`${o} bigint`;else if(n==="float")a=true,s=`${o} float`;else if(n==="double")a=true,s=`${o} double`;else if(n==="real")a=true,s=`${o} double`;else if(n==="decimal"){a=true;let u=e.precision??10,d=e.scale??0;s=`${o} decimal(${u}, ${d})`;}else if(n==="numeric"){a=true;let u=e.precision??10,d=e.scale??0;s=`${o} numeric(${u}, ${d})`;}else if(n==="date")s=`${o} date`;else if(n==="time"){let u=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} time${u}`.trimEnd();}else if(n==="datetime"){let u=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} datetime${u}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${u}`),e.autoUpdate&&(s+=` on update current_timestamp${u}`);}else if(n==="timestamp"){let u=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} timestamp${u}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${u}`),e.autoUpdate&&(s+=` on update current_timestamp${u}`);}else if(n==="year")s=`${o} year`;else if(n==="boolean")s=`${o} boolean`;else if(n==="varbinary"){let u=e.length??255;s=`${o} varbinary(${u})`;}else if(n==="binary"){let u=e.length??255;s=`${o} binary(${u})`;}else if(n==="bytea"||n==="blob")s=`${o} blob`;else if(n==="json"||n==="jsonb")s=`${o} json`;else if(n==="enum")if(e.enumValues&&e.enumValues.length>0){let u=e.enumValues.map(d=>`'${d}'`).join(", ");s=`${o} enum(${u})`;}else s=`${o} text`;else if(n==="geometry")s=`${o} geometry`;else if(n==="point")s=`${o} point`;else if(n==="linestring")s=`${o} linestring`;else if(n==="polygon")s=`${o} polygon`;else if(n==="multipoint")s=`${o} multipoint`;else {let u=e.length?`(${e.length})`:"";s=`${o} ${n}${u}`;}return a&&(e.zerofill?s+=" ZEROFILL":e.unsigned&&(s+=" UNSIGNED"),l&&(s+=" AUTO_INCREMENT")),e.collate&&(s+=` COLLATE ${e.collate}`),{sql:s,bindings:[]}}},Wu=new mn;var pn=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},ju=new pn;var fn=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 P?{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(u=>r.formatStringColumn("mysql",N(u))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("mysql",N(u))).join(", "),l=`${e.constraintName?`constraint \`${e.constraintName}\` `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Fu=new fn;var yn=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 T(this.model,"mysql"),s=[],a=[];for(let m of e.children){let{sql:g,bindings:f}=n.parse([m]);if(m.folder==="constraint"){let b=s.pop()??"",w=g;if(/not null/i.test(w)||/null/i.test(w)||/default/i.test(w)){let q=`${b} ${w}`.trim();q=q.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(q),a.push(...f);continue}s.push(b),s.push(w),a.push(...f);continue}s.push(g),a.push(...f);}for(let m of e.namedConstraints){let{sql:g,bindings:f}=n.parse([m]);s.push(g),a.push(...f);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.engine&&d.push(`ENGINE=${e.engine}`),e.charset&&d.push(`CHARSET=${e.charset}`),e.collate&&d.push(`COLLATE=${e.collate}`);let p=d.length>0?` ${d.join(" ")}`:"";return {sql:`${u}${o} (${l})${p}`,bindings:a}}},Uu=new yn;var hn=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:[]}}},Vu=new hn;var gn=class{toSql(t){return {sql:"distinct",bindings:[]}}},Ju=new gn;var bn=class{toSql(t){return _.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},Hu=new bn;var Tn=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},zu=new Tn;var wn=class{toSql(t){return {sql:`-- MySQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Yu=new wn;var Sn=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 T(this.model,"mysql").parse(r),s=e.alias&&e.alias.length?` as \`${e.alias}\``:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Gu=new Sn;var Nn=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},Zu=new Nn;var qn=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 S)&&!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}}},Xu=new qn;var Cn=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:[]}}},ed=new Cn;var Rn=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:[]}}},td=new Rn;var Mn=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(p=>r.formatStringColumn("mysql",p)).join(", "),l=[],u=[];for(let p of e.records){let c=s.map(g=>p[g]),m=[];for(let g of c)g instanceof P?m.push(g.rawValue):(l.push(g),m.push("?"));u.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${u.join(", ")}`,bindings:l}}},rd=new Mn;var _n=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),u=`${r.formatStringTable("mysql",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"mysql");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},od=new _n;var On=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},nd=new On;var jf={for_update:"for update",for_share:"lock in share mode"},An=class{toSql(t){let e=t,r=jf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},sd=new An;var xn=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},id=new xn;var Dn=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:[]}}},ad=new Dn;var In=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:[]}}},ld=new In;var Pn=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},ud=new Pn;var $n=class{toSql(t){return {sql:`SELECT
|
|
53
|
+
ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},Tu=new Lo;var Wo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("mssql",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new T(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 T(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 T(this.model,"mssql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as [${t}]`:""}},wu=new Wo;var ce=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 jo=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=ce.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}},Nu=new jo;var Fo=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:[]}}},Su=new Fo;var Uo=class{toSql(t){let e=t,r=new T(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}}},qu=new Uo;var Vo=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((u,d)=>{let p=e.currParamIndex+d-n,c=e.values[d];return c instanceof $?(n++,`${r.formatStringColumn("mssql",u)} = ${c.rawValue}`):(s.push(c),`${r.formatStringColumn("mssql",u)} = @${p}`)}).join(", "),l=`${o} set ${a}`;if(e.returning&&e.returning.length){let u=e.returning.map(d=>`inserted.${r.formatStringColumn("mssql",d)}`).join(", ");l+=` output ${u}`;}return {sql:l,bindings:s}}},Cu=new Vo;var Jo=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 d=`@${o} AND @${o+1}`,p=`${a} between ${d}`;return e.isNegated&&(p=`not (${p})`),{sql:p.trim(),bindings:r}}let l=r.map((d,p)=>`@${o+p}`).join(", "),u=`${a} ${e.operator} (${l})`;return e.isNegated&&(u=`not (${u})`),{sql:u.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}},Ru=new Jo;var Ho=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new T(this.model,"mssql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Mu=new Ho;var zo=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}}},_u=new zo;var Yo=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"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 T(this.model,"mssql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Ou=new Yo;var Go=class{toSql(t){let e=t,r=new T(this.model,"mssql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return e.clause==="materialized"&&_.warn("MSSQL does not support MATERIALIZED CTEs. The clause will be ignored."),{sql:`[${e.alias}] as (${n.sql})`,bindings:n.bindings}}},Au=new Go;var Zo=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},xu=new Zo;var Xo=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Du=new Xo;var en=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`\`${o}\``).join(", ")})`,bindings:[]}}},Iu=new en;var tn=class{toSql(t){let e=t,r=new T(this.model,"mysql"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" "),a=`modify column \`${e.column}\` ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?"":" not null";a+=l;}if(!e.options.dropDefault){if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=` default ${l}`;}}return e.options.collate&&(a+=` COLLATE ${e.options.collate}`),e.options.unique!==void 0&&e.options.unique&&(a+=" unique"),{sql:a,bindings:[]}}},$u=new tn;var rn=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 T(this.model,"mysql"),s=[],a=[];for(let c of e.children){let{sql:m,bindings:g}=n.parse([c]);if(c.file==="add_column")s.push(m);else if(c.file==="add_constraint"||c.folder==="constraint"){let f=s[s.length-1]??"",b=/^\s*add\s+column\b/i.test(f),w=/^\s*add\s+constraint\b/i.test(m);if(b&&!w){let q=m.replace(/^\s*add\s+/i,"").trimStart();s[s.length-1]=`${f} ${q}`;}else {let q=/^\s*add\b/i.test(m)?m:`add ${m}`;s.push(q);}}else c.file==="set_default"||c.file==="drop_default"||c.file==="set_not_null"||c.file,s.push(m);a.push(...g);}let l=s.join(", "),u=e.ifExists?"if exists ":"";return {sql:/^\s*drop\s+index\b/i.test(l)?l:`${u}${o} ${l}`,bindings:a}}},Pu=new rn;var on=class{toSql(t){return {sql:`drop column \`${t.column}\``,bindings:[]}}},Eu=new on;var nn=class{toSql(t){return {sql:`drop constraint \`${t.constraintName}\``,bindings:[]}}},vu=new nn;var sn=class{toSql(t){return {sql:`alter column \`${t.column}\` drop default`,bindings:[]}}},Bu=new sn;var an=class{toSql(t){return {sql:"",bindings:[]}}},Ku=new an;var ln=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Qu=new ln;var un=class{toSql(t){let e=t;return {sql:`rename column \`${e.oldName}\` to \`${e.newName}\``,bindings:[]}}},ku=new un;var dn=class{toSql(t){return {sql:`\`${t.newName}\``,bindings:[]}}},Lu=new dn;var cn=class{toSql(t){let e=t,r;return e.defaultValue instanceof $?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:[]}}},Wu=new cn;var mn=class{toSql(t){return {sql:"",bindings:[]}}},ju=new mn;var pn=class{toSql(t){let e=t,r=[];return e.engine&&r.push(`ENGINE=${e.engine}`),e.charset&&r.push(`CHARSET=${e.charset}`),e.collate&&r.push(`COLLATE=${e.collate}`),{sql:r.join(" "),bindings:[]}}},Fu=new pn;var fn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("mysql",S(e.column)),n=e.dataType.toLowerCase(),s,a=false,l=false;if(n==="char"){let u=e.length??1;s=`${o} char(${u})`;}else if(n==="varchar"){let u=e.length??255;s=`${o} varchar(${u})`;}else if(n==="uuid")s=`${o} varchar(36)`;else if(n==="ulid")s=`${o} varchar(26)`;else if(n==="longtext"||n==="mediumtext"||n==="tinytext"||n==="text")s=`${o} ${n}`;else if(n==="integer"||n==="int")a=true,l=!!e.autoIncrement,s=`${o} int`;else if(n==="tinyint")a=true,s=`${o} tinyint`;else if(n==="smallint")a=true,s=`${o} smallint`;else if(n==="mediumint")a=true,s=`${o} mediumint`;else if(n==="bigint")a=true,l=!!e.autoIncrement,s=`${o} bigint`;else if(n==="float")a=true,s=`${o} float`;else if(n==="double")a=true,s=`${o} double`;else if(n==="real")a=true,s=`${o} double`;else if(n==="decimal"){a=true;let u=e.precision??10,d=e.scale??0;s=`${o} decimal(${u}, ${d})`;}else if(n==="numeric"){a=true;let u=e.precision??10,d=e.scale??0;s=`${o} numeric(${u}, ${d})`;}else if(n==="date")s=`${o} date`;else if(n==="time"){let u=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} time${u}`.trimEnd();}else if(n==="datetime"){let u=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} datetime${u}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${u}`),e.autoUpdate&&(s+=` on update current_timestamp${u}`);}else if(n==="timestamp"){let u=typeof e.precision=="number"?`(${e.precision})`:"";s=`${o} timestamp${u}`.trimEnd(),e.autoCreate&&(s+=` default current_timestamp${u}`),e.autoUpdate&&(s+=` on update current_timestamp${u}`);}else if(n==="year")s=`${o} year`;else if(n==="boolean")s=`${o} boolean`;else if(n==="varbinary"){let u=e.length??255;s=`${o} varbinary(${u})`;}else if(n==="binary"){let u=e.length??255;s=`${o} binary(${u})`;}else if(n==="bytea"||n==="blob")s=`${o} blob`;else if(n==="json"||n==="jsonb")s=`${o} json`;else if(n==="enum")if(e.enumValues&&e.enumValues.length>0){let u=e.enumValues.map(d=>`'${d}'`).join(", ");s=`${o} enum(${u})`;}else s=`${o} text`;else if(n==="geometry")s=`${o} geometry`;else if(n==="point")s=`${o} point`;else if(n==="linestring")s=`${o} linestring`;else if(n==="polygon")s=`${o} polygon`;else if(n==="multipoint")s=`${o} multipoint`;else {let u=e.length?`(${e.length})`:"";s=`${o} ${n}${u}`;}return a&&(e.zerofill?s+=" ZEROFILL":e.unsigned&&(s+=" UNSIGNED"),l&&(s+=" AUTO_INCREMENT")),e.collate&&(s+=` COLLATE ${e.collate}`),{sql:s,bindings:[]}}},Uu=new fn;var yn=class{toSql(t){return {sql:`after \`${t.column}\``,bindings:[]}}},Vu=new yn;var hn=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",S(s))).join(", ");return {sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}primary key (${o})`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns.map(s=>r.formatStringColumn("mysql",S(s))).join(", "),n=e.constraintName?`constraint \`${e.constraintName}\` `:"";return e.constraintName?{sql:`${n}unique (${o})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let o=e.defaultValue;return o instanceof $?{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(u=>r.formatStringColumn("mysql",S(u))).join(", "),n=r.formatStringTable("mysql",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("mysql",S(u))).join(", "),l=`${e.constraintName?`constraint \`${e.constraintName}\` `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint \`${e.constraintName}\` `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Ju=new hn;var gn=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 T(this.model,"mysql"),s=[],a=[];for(let m of e.children){let{sql:g,bindings:f}=n.parse([m]);if(m.folder==="constraint"){let b=s.pop()??"",w=g;if(/not null/i.test(w)||/null/i.test(w)||/default/i.test(w)){let q=`${b} ${w}`.trim();q=q.replace(/(references\s+`[^`]+`\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(q),a.push(...f);continue}s.push(b),s.push(w),a.push(...f);continue}s.push(g),a.push(...f);}for(let m of e.namedConstraints){let{sql:g,bindings:f}=n.parse([m]);s.push(g),a.push(...f);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.engine&&d.push(`ENGINE=${e.engine}`),e.charset&&d.push(`CHARSET=${e.charset}`),e.collate&&d.push(`COLLATE=${e.collate}`);let p=d.length>0?` ${d.join(" ")}`:"";return {sql:`${u}${o} (${l})${p}`,bindings:a}}},Hu=new gn;var bn=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:[]}}},zu=new bn;var Tn=class{toSql(t){return {sql:"distinct",bindings:[]}}},Yu=new Tn;var wn=class{toSql(t){return _.warn("MySQL does not support DISTINCT ON"),{sql:"",bindings:[]}}},Gu=new wn;var Nn=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("mysql",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Zu=new Nn;var Sn=class{toSql(t){return {sql:`-- MySQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Xu=new Sn;var qn=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 T(this.model,"mysql").parse(r),s=e.alias&&e.alias.length?` as \`${e.alias}\``:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},ed=new qn;var Cn=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mysql",e.column),bindings:[]}}},td=new Cn;var Rn=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 N)&&!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}}},rd=new Rn;var Mn=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:[]}}},od=new Mn;var _n=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:[]}}},nd=new _n;var On=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(p=>r.formatStringColumn("mysql",p)).join(", "),l=[],u=[];for(let p of e.records){let c=s.map(g=>p[g]),m=[];for(let g of c)g instanceof $?m.push(g.rawValue):(l.push(g),m.push("?"));u.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${u.join(", ")}`,bindings:l}}},sd=new On;var An=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),u=`${r.formatStringTable("mysql",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"mysql");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},id=new An;var xn=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},ad=new xn;var Vf={for_update:"for update",for_share:"lock in share mode"},Dn=class{toSql(t){let e=t,r=Vf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),{sql:r,bindings:[]}}},ld=new Dn;var In=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},ud=new In;var $n=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:[]}}},dd=new $n;var Pn=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:[]}}},cd=new Pn;var En=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},md=new En;var vn=class{toSql(t){return {sql:`SELECT
|
|
54
54
|
cc.CONSTRAINT_NAME AS name,
|
|
55
55
|
cc.CHECK_CLAUSE AS expression
|
|
56
56
|
FROM information_schema.CHECK_CONSTRAINTS cc
|
|
@@ -59,7 +59,7 @@ ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},hu=new Ko;var ko=class{toSql(t){let
|
|
|
59
59
|
AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
|
|
60
60
|
WHERE tc.TABLE_SCHEMA = DATABASE()
|
|
61
61
|
AND tc.TABLE_NAME = '${t.table}'
|
|
62
|
-
AND tc.CONSTRAINT_TYPE = 'CHECK'`,bindings:[]}}},
|
|
62
|
+
AND tc.CONSTRAINT_TYPE = 'CHECK'`,bindings:[]}}},pd=new vn;var Bn=class{toSql(t){return {sql:`SELECT
|
|
63
63
|
k.CONSTRAINT_NAME AS name,
|
|
64
64
|
k.COLUMN_NAME AS column_name,
|
|
65
65
|
k.REFERENCED_TABLE_NAME AS referenced_table,
|
|
@@ -70,18 +70,18 @@ ORDER BY c.ORDINAL_POSITION`,bindings:[]}}},hu=new Ko;var ko=class{toSql(t){let
|
|
|
70
70
|
JOIN information_schema.REFERENTIAL_CONSTRAINTS r
|
|
71
71
|
ON k.CONSTRAINT_NAME = r.CONSTRAINT_NAME AND k.CONSTRAINT_SCHEMA = r.CONSTRAINT_SCHEMA
|
|
72
72
|
WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.REFERENCED_TABLE_NAME IS NOT NULL
|
|
73
|
-
ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},
|
|
73
|
+
ORDER BY k.POSITION_IN_UNIQUE_CONSTRAINT`,bindings:[]}}},fd=new Bn;var Kn=class{toSql(t){return {sql:`SHOW INDEX FROM \`${t.table}\``,bindings:[]}}},yd=new Kn;var Qn=class{toSql(t){return {sql:`SELECT
|
|
74
74
|
CONSTRAINT_NAME AS name,
|
|
75
75
|
COLUMN_NAME AS column_name
|
|
76
76
|
FROM information_schema.KEY_COLUMN_USAGE k
|
|
77
77
|
WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = '${t.table}' AND k.CONSTRAINT_NAME = 'PRIMARY'
|
|
78
|
-
ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},pd=new Bn;var Qn=class{toSql(t){return {sql:`SELECT COLUMN_NAME AS column_name, DATA_TYPE AS data_type, COLUMN_TYPE AS column_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:[]}}},fd=new Qn;var Kn=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 T(this.model,"mysql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"mysql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("mysql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"mysql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length?` as \`${t}\``:""}},yd=new Kn;var kn=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=ce.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}},hd=new kn;var Ln=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:[]}}},gd=new Ln;var Wn=class{toSql(t){let e=t,r=new T(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},bd=new Wn;var jn=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new 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 u=e.values[l];return u instanceof P?`${r.formatStringColumn("mysql",a)} = ${u.rawValue}`:(n.push(u),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},Td=new jn;var Fn=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}},wd=new Fn;var Un=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new T(this.model,"mysql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Sd=new Un;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}}},Nd=new Vn;var Jn=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"mysql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"mysql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},qd=new Jn;var Hn=class{toSql(t){let e=t,r=new T(this.model,"mysql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},Cd=new Hn;var zn=class{toSql(t){let e=t,r=new T(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:[]}}},Rd=new zn;var Yn=class{toSql(t){let e=t,r=new T(this.model,"oracledb"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Md=new Yn;var Gn=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},_d=new Gn;var Zn=class{toSql(t){let e=t,r=new T(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:[]}}},Od=new Zn;var Xn=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 T(this.model,"oracledb"),s=[],a=[];for(let d of e.children){let{sql:p,bindings:c}=n.parse([d]);s.push(p.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},Ad=new Xn;var es=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},xd=new es;var ts=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Dd=new ts;var rs=class{toSql(t){return {sql:`modify "${t.column}" default null`,bindings:[]}}},Id=new rs;var os=class{toSql(t){return {sql:`modify "${t.column}" null`,bindings:[]}}},Pd=new os;var ns=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},$d=new ns;var ss=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Ed=new ss;var is=class{toSql(t){return {sql:`rename to "${t.newName}"`,bindings:[]}}},vd=new is;var as=class{toSql(t){let e=t,r;return e.defaultValue instanceof P?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:[]}}},Bd=new as;var ls=class{toSql(t){return {sql:`modify "${t.column}" not null`,bindings:[]}}},Qd=new ls;var us=class{toSql(t){return {sql:"",bindings:[]}}},Kd=new us;var ds=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 a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}else if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar2(${a})`,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 a=e.precision??10,l=e.scale??0;return {sql:`${o} number(${a}, ${l})`,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 a=e.withTimezone?" with time zone":"",l=typeof e.precision=="number"?`(${e.precision})`:"",u=`${o} timestamp${l}${a}`.trimEnd();return e.autoCreate&&(u+=" default current_timestamp"),{sql:u,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 a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} varchar2(255) check (${o} in (${a}))`,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:[]}}}}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},kd=new ds;var cs=class{toSql(t){return {sql:"",bindings:[]}}},Ld=new cs;var ms=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 P?{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(u=>r.formatStringColumn("oracledb",N(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("oracledb",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("oracledb",N(u))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Wd=new ms;var ps=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 T(this.model,"oracledb"),s=[],a=[];for(let c of e.children){let{sql:m,bindings:g}=n.parse([c]);if(c.folder==="constraint"){let f=s.pop()??"",b=m;if(/not null/i.test(b)||/null/i.test(b)||/default/i.test(b)){let w=`${f} ${b}`.trim();w=w.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(w),a.push(...g);continue}s.push(f),s.push(b),a.push(...g);continue}s.push(m),a.push(...g);}for(let c of e.namedConstraints){let{sql:m,bindings:g}=n.parse([c]);s.push(m),a.push(...g);}let l=s.join(", "),u=[];if(e.oracleTablespace&&u.push(`TABLESPACE ${e.oracleTablespace}`),e.oracleCompress?u.push("COMPRESS"):e.oracleCompressFor&&u.push(`COMPRESS FOR ${e.oracleCompressFor}`),e.oracleStorage){let c=Object.entries(e.oracleStorage).map(([m,g])=>`${m.toUpperCase()} ${g}`).join(" ");c&&u.push(`STORAGE (${c})`);}e.oracleLogging===false?u.push("NOLOGGING"):e.oracleLogging===true&&u.push("LOGGING"),e.oracleCache===false?u.push("NOCACHE"):e.oracleCache===true&&u.push("CACHE"),e.oracleInMemory&&u.push("INMEMORY");let d=u.length>0?` ${u.join(" ")}`:"";return {sql:`${o} (${l})${d}`,bindings:a}}},jd=new ps;var fs=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:[]}}},Fd=new fs;var ys=class{toSql(t){return {sql:"",bindings:[]}}},Ud=new ys;var hs=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("oracledb",o)).join(", ")})`,bindings:[]}}},Vd=new hs;var gs=class{toSql(t){let e=t;return {sql:`${new y(this.model).formatStringTable("oracledb",e.table)} cascade constraints`,bindings:[]}}},Jd=new gs;var bs=class{toSql(t){return {sql:`-- Oracle does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Hd=new bs;var Ts=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 T(this.model,"oracledb").parse(r),s=e.alias&&e.alias.length?` "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},zd=new Ts;var ws=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("oracledb",e.column),bindings:[]}}},Yd=new ws;var Ss=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 S)&&!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}}},Gd=new Ss;var Ns=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:[]}}},Zd=new Ns;var qs=class{toSql(t){return {sql:`"${t.indexName}"`,bindings:[]}}},Xd=new qs;var Cs=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=[],u=[],d=e.currParamIndex;for(let c of e.records){let m=s.map(f=>c[f]),g=[];for(let f of m)f instanceof P?g.push(f.rawValue):(l.push(f),g.push(`:${d++}`));u.push(`(${g.join(", ")})`);}let p;if(e.records.length===1)p=`${o} (${a}) values ${u[0]}`;else {e.keyword="insert",d=e.currParamIndex;let c=[];for(let m of e.records){let g=s.map(b=>m[b]),f=[];for(let b of g)b instanceof P?f.push(b.rawValue):f.push(`:${d++}`);c.push(`into ${o} (${a}) values (${f.join(", ")})`);}p=`all ${c.join(" ")} select * from dual`;}return {sql:p,bindings:l}}},ec=new Cs;var Rs=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),u=`${r.formatStringTable("oracledb",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"oracledb");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},tc=new Rs;var Ms=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.limit]}}},rc=new Ms;var Ff={for_update:"for update",for_share:"for update",for_no_key_update:"for update",for_key_share:"for update"},_s=class{toSql(t){let e=t,r=Ff[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},oc=new _s;var Os=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.offset]}}},nc=new Os;var As=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:[]}}},sc=new As;var xs=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:[]}}},ic=new xs;var Ds=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},ac=new Ds;var Is=class{toSql(t){return {sql:`SELECT
|
|
78
|
+
ORDER BY k.ORDINAL_POSITION`,bindings:[]}}},hd=new Qn;var kn=class{toSql(t){return {sql:`SELECT COLUMN_NAME AS column_name, DATA_TYPE AS data_type, COLUMN_TYPE AS column_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:[]}}},gd=new kn;var Ln=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 T(this.model,"mysql").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"mysql").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("mysql",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"mysql").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length?` as \`${t}\``:""}},bd=new Ln;var Wn=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=ce.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}},Td=new Wn;var jn=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:[]}}},wd=new jn;var Fn=class{toSql(t){let e=t,r=new T(this.model,"mysql"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},Nd=new Fn;var Un=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 u=e.values[l];return u instanceof $?`${r.formatStringColumn("mysql",a)} = ${u.rawValue}`:(n.push(u),`${r.formatStringColumn("mysql",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},Sd=new Un;var Vn=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}},qd=new Vn;var Jn=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new T(this.model,"mysql"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Cd=new Jn;var Hn=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}}},Rd=new Hn;var zn=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"mysql"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"mysql"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Md=new zn;var Yn=class{toSql(t){let e=t,r=new T(this.model,"mysql"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},_d=new Yn;var Gn=class{toSql(t){let e=t,r=new T(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:[]}}},Od=new Gn;var Zn=class{toSql(t){let e=t,r=new T(this.model,"oracledb"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Ad=new Zn;var Xn=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},xd=new Xn;var es=class{toSql(t){let e=t,r=new T(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:[]}}},Dd=new es;var ts=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 T(this.model,"oracledb"),s=[],a=[];for(let d of e.children){let{sql:p,bindings:c}=n.parse([d]);s.push(p.trim()),a.push(...c);}let l=s.join(", ");return {sql:`${o} ${l}`,bindings:a}}},Id=new ts;var rs=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},$d=new rs;var os=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Pd=new os;var ns=class{toSql(t){return {sql:`modify "${t.column}" default null`,bindings:[]}}},Ed=new ns;var ss=class{toSql(t){return {sql:`modify "${t.column}" null`,bindings:[]}}},vd=new ss;var is=class{toSql(t){return {sql:"drop primary key",bindings:[]}}},Bd=new is;var as=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Kd=new as;var ls=class{toSql(t){return {sql:`rename to "${t.newName}"`,bindings:[]}}},Qd=new ls;var us=class{toSql(t){let e=t,r;return e.defaultValue instanceof $?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:[]}}},kd=new us;var ds=class{toSql(t){return {sql:`modify "${t.column}" not null`,bindings:[]}}},Ld=new ds;var cs=class{toSql(t){return {sql:"",bindings:[]}}},Wd=new cs;var ms=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("oracledb",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}else if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar2(${a})`,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 a=e.precision??10,l=e.scale??0;return {sql:`${o} number(${a}, ${l})`,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 a=e.withTimezone?" with time zone":"",l=typeof e.precision=="number"?`(${e.precision})`:"",u=`${o} timestamp${l}${a}`.trimEnd();return e.autoCreate&&(u+=" default current_timestamp"),{sql:u,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 a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} varchar2(255) check (${o} in (${a}))`,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:[]}}}}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},jd=new ms;var ps=class{toSql(t){return {sql:"",bindings:[]}}},Fd=new ps;var fs=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",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("oracledb",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof $?{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(u=>r.formatStringColumn("oracledb",S(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("oracledb",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("oracledb",S(u))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Ud=new fs;var ys=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 T(this.model,"oracledb"),s=[],a=[];for(let c of e.children){let{sql:m,bindings:g}=n.parse([c]);if(c.folder==="constraint"){let f=s.pop()??"",b=m;if(/not null/i.test(b)||/null/i.test(b)||/default/i.test(b)){let w=`${f} ${b}`.trim();w=w.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(w),a.push(...g);continue}s.push(f),s.push(b),a.push(...g);continue}s.push(m),a.push(...g);}for(let c of e.namedConstraints){let{sql:m,bindings:g}=n.parse([c]);s.push(m),a.push(...g);}let l=s.join(", "),u=[];if(e.oracleTablespace&&u.push(`TABLESPACE ${e.oracleTablespace}`),e.oracleCompress?u.push("COMPRESS"):e.oracleCompressFor&&u.push(`COMPRESS FOR ${e.oracleCompressFor}`),e.oracleStorage){let c=Object.entries(e.oracleStorage).map(([m,g])=>`${m.toUpperCase()} ${g}`).join(" ");c&&u.push(`STORAGE (${c})`);}e.oracleLogging===false?u.push("NOLOGGING"):e.oracleLogging===true&&u.push("LOGGING"),e.oracleCache===false?u.push("NOCACHE"):e.oracleCache===true&&u.push("CACHE"),e.oracleInMemory&&u.push("INMEMORY");let d=u.length>0?` ${u.join(" ")}`:"";return {sql:`${o} (${l})${d}`,bindings:a}}},Vd=new ys;var hs=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:[]}}},Jd=new hs;var gs=class{toSql(t){return {sql:"",bindings:[]}}},Hd=new gs;var bs=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("oracledb",o)).join(", ")})`,bindings:[]}}},zd=new bs;var Ts=class{toSql(t){let e=t;return {sql:`${new y(this.model).formatStringTable("oracledb",e.table)} cascade constraints`,bindings:[]}}},Yd=new Ts;var ws=class{toSql(t){return {sql:`-- Oracle does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},Gd=new ws;var Ns=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 T(this.model,"oracledb").parse(r),s=e.alias&&e.alias.length?` "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Zd=new Ns;var Ss=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("oracledb",e.column),bindings:[]}}},Xd=new Ss;var qs=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 N)&&!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}}},ec=new qs;var Cs=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:[]}}},tc=new Cs;var Rs=class{toSql(t){return {sql:`"${t.indexName}"`,bindings:[]}}},rc=new Rs;var Ms=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=[],u=[],d=e.currParamIndex;for(let c of e.records){let m=s.map(f=>c[f]),g=[];for(let f of m)f instanceof $?g.push(f.rawValue):(l.push(f),g.push(`:${d++}`));u.push(`(${g.join(", ")})`);}let p;if(e.records.length===1)p=`${o} (${a}) values ${u[0]}`;else {e.keyword="insert",d=e.currParamIndex;let c=[];for(let m of e.records){let g=s.map(b=>m[b]),f=[];for(let b of g)b instanceof $?f.push(b.rawValue):f.push(`:${d++}`);c.push(`into ${o} (${a}) values (${f.join(", ")})`);}p=`all ${c.join(" ")} select * from dual`;}return {sql:p,bindings:l}}},oc=new Ms;var _s=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),u=`${r.formatStringTable("oracledb",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"oracledb");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},nc=new _s;var Os=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.limit]}}},sc=new Os;var Jf={for_update:"for update",for_share:"for update",for_no_key_update:"for update",for_key_share:"for update"},As=class{toSql(t){let e=t,r=Jf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},ic=new As;var xs=class{toSql(t){let e=t;return {sql:`:${e.currParamIndex}`,bindings:[e.offset]}}},ac=new xs;var Ds=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:[]}}},lc=new Ds;var Is=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:[]}}},uc=new Is;var $s=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},dc=new $s;var Ps=class{toSql(t){return {sql:`SELECT
|
|
79
79
|
constraint_name AS name,
|
|
80
80
|
search_condition AS expression
|
|
81
81
|
FROM user_constraints
|
|
82
82
|
WHERE table_name = '${t.table.toUpperCase()}'
|
|
83
83
|
AND constraint_type = 'C'
|
|
84
|
-
AND constraint_name NOT LIKE 'SYS_%'`,bindings:[]}}},
|
|
84
|
+
AND constraint_name NOT LIKE 'SYS_%'`,bindings:[]}}},cc=new Ps;var Es=class{toSql(t){return {sql:`SELECT
|
|
85
85
|
c.constraint_name as name,
|
|
86
86
|
cc.column_name as column_name,
|
|
87
87
|
rc.table_name as referenced_table,
|
|
@@ -93,7 +93,7 @@ JOIN user_constraints rc ON c.r_constraint_name = rc.constraint_name
|
|
|
93
93
|
JOIN user_cons_columns rcc ON rc.constraint_name = rcc.constraint_name AND cc.position = rcc.position
|
|
94
94
|
WHERE c.constraint_type = 'R'
|
|
95
95
|
AND c.table_name = '${t.table.toUpperCase()}'
|
|
96
|
-
ORDER BY cc.position`,bindings:[]}}},
|
|
96
|
+
ORDER BY cc.position`,bindings:[]}}},mc=new Es;var vs=class{toSql(t){return {sql:`SELECT
|
|
97
97
|
i.index_name as index_name,
|
|
98
98
|
ic.column_name as column_name,
|
|
99
99
|
CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END as is_unique
|
|
@@ -106,14 +106,14 @@ WHERE i.table_name = '${t.table.toUpperCase()}'
|
|
|
106
106
|
WHERE c.constraint_type = 'P'
|
|
107
107
|
AND c.index_name = i.index_name
|
|
108
108
|
)
|
|
109
|
-
ORDER BY i.index_name, ic.column_position`,bindings:[]}}},
|
|
109
|
+
ORDER BY i.index_name, ic.column_position`,bindings:[]}}},pc=new vs;var Bs=class{toSql(t){return {sql:`SELECT
|
|
110
110
|
c.constraint_name as name,
|
|
111
111
|
cc.column_name as column_name
|
|
112
112
|
FROM user_constraints c
|
|
113
113
|
JOIN user_cons_columns cc ON c.constraint_name = cc.constraint_name
|
|
114
114
|
WHERE c.constraint_type = 'P'
|
|
115
115
|
AND c.table_name = '${t.table.toUpperCase()}'
|
|
116
|
-
ORDER BY cc.position`,bindings:[]}}},
|
|
116
|
+
ORDER BY cc.position`,bindings:[]}}},fc=new Bs;var Ks=class{toSql(t){return {sql:`SELECT
|
|
117
117
|
column_name,
|
|
118
118
|
data_type,
|
|
119
119
|
CASE WHEN nullable = 'Y' THEN 'YES' ELSE 'NO' END as is_nullable,
|
|
@@ -123,7 +123,7 @@ ORDER BY cc.position`,bindings:[]}}},cc=new Es;var vs=class{toSql(t){return {sql
|
|
|
123
123
|
data_scale as numeric_scale
|
|
124
124
|
FROM user_tab_columns
|
|
125
125
|
WHERE table_name = '${t.table.toUpperCase()}'
|
|
126
|
-
ORDER BY column_id`,bindings:[]}}},mc=new vs;var Bs=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 T(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 T(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 T(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},pc=new Bs;var Qs=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=ce.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toOracle();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.size()')`:`JSON_QUERY(${t}, '${r}.size()')`}buildObjectKeysSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.keyNames()')`:`JSON_QUERY(${t}, '${r}.keyNames()')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},fc=new Qs;var Ks=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:[]}}},yc=new Ks;var ks=class{toSql(t){let e=t,r=new T(this.model,"oracledb"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},hc=new ks;var Ls=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,u)=>{let d=e.values[u];return d instanceof P?`${r.formatStringColumn("oracledb",l)} = ${d.rawValue}`:(s.push(d),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},gc=new Ls;var Ws=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}},bc=new Ws;var js=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new T(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Tc=new js;var Fs=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}}},wc=new Fs;var Us=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"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 T(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Sc=new Us;var Vs=class{toSql(t){let e=t,r=new T(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}}},Nc=new Vs;var Js=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},qc=new Js;var Hs=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Cc=new Hs;var zs=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Rc=new zs;var Ys=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" ");s=s.replace(/\s*check\s*\(.*\)\s*$/i,"").trim();let 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:[]}}},Mc=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:"",bindings:[]};let n=new T(this.model,"postgres"),s=[],a=[];for(let p of e.children){let{sql:c,bindings:m}=n.parse([p]);s.push(c.trim()),a.push(...m);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},_c=new Gs;var Zs=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Oc=new Zs;var Xs=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Ac=new Xs;var ei=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},xc=new ei;var ti=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Dc=new ti;var ri=class{toSql(t){return {sql:"",bindings:[]}}},Ic=new ri;var oi=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},Pc=new oi;var ni=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},$c=new ni;var si=class{toSql(t){let e=t,r;return e.defaultValue instanceof P?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 si;var ii=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},vc=new ii;var ai=class{toSql(t){return {sql:"",bindings:[]}}},Bc=new ai;var li=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 a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}else if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar(${a})`,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 a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${a}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let a=e.withTimezone?" with time zone":" without time zone",l=typeof e.precision=="number"?`(${e.precision})`:"",u=`${o} timestamp${l}${a}`.trimEnd();return e.autoCreate&&(u+=" default current_timestamp"),{sql:u,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 a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} text check (${o} in (${a}))`,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:[]}}}}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},Qc=new li;var ui=class{toSql(t){return {sql:"",bindings:[]}}},Kc=new ui;var di=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 P?{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(u=>r.formatStringColumn("postgres",N(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("postgres",N(u))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},kc=new di;var ci=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 T(this.model,"postgres"),s=[],a=[];for(let w of e.children){let{sql:q,bindings:M}=n.parse([w]);if(w.folder==="constraint"){let R=s.pop()??"",A=q;if(/not null/i.test(A)||/null/i.test(A)||/default/i.test(A)){let D=`${R} ${A}`.trim();D=D.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(D),a.push(...M);continue}s.push(R),s.push(A),a.push(...M);continue}s.push(q),a.push(...M);}for(let w of e.namedConstraints){let{sql:q,bindings:M}=n.parse([w]);s.push(q),a.push(...M);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.temporary&&d.push("TEMPORARY"),e.unlogged&&d.push("UNLOGGED");let p=[];if(e.postgresWith){let w=Object.entries(e.postgresWith).map(([q,M])=>`${q}=${M}`).join(", ");w&&p.push(`WITH (${w})`);}let c=e.tablespace?`TABLESPACE ${e.tablespace}`:"",m=d.length>0?`${d.join(" ")} `:"",g=p.length>0?` ${p.join(" ")}`:"",f=c?` ${c}`:"";return {sql:`${u}${m}${o} (${l})${g}${f}`,bindings:a}}},Lc=new ci;var mi=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode.table=="string")return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),n=r.getFromForWriteOperations("postgres",e.fromNode);if(e.returning&&e.returning.length){let s=e.returning.map(a=>r.formatStringColumn("postgres",a)).join(", ");n+=` returning ${s}`;}return {sql:n,bindings:[]}}},Wc=new mi;var pi=class{toSql(t){return {sql:"",bindings:[]}}},jc=new pi;var fi=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},Fc=new fi;var yi=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Uc=new yi;var hi=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},Vc=new hi;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("postgres",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("postgres",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new T(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Jc=new gi;var bi=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},Hc=new bi;var Ti=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 S)&&!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}}},zc=new Ti;var wi=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:[]}}},Yc=new wi;var Si=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},Gc=new Si;var Ni=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=[],u=[],d=e.currParamIndex;for(let c of e.records){let m=s.map(f=>c[f]),g=[];for(let f=0;f<s.length;f++){let b=m[f];b instanceof P?g.push(b.rawValue):(l.push(b),g.push(`$${d++}${this.formatTypeCast(b)}`));}u.push(`(${g.join(", ")})`);}let p=`${o} (${a}) values ${u.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(m=>r.formatStringColumn("postgres",m)).join(", ");p+=` returning ${c}`;}else p+=" returning *";return {sql:p,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Zc=new Ni;var qi=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),u=`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"postgres");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},Xc=new qi;var Ci=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},em=new Ci;var Uf={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},Ri=class{toSql(t){let e=t,r=Uf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},tm=new Ri;var Mi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},rm=new Mi;var _i=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"){let a=`on conflict (${o}) do nothing`;if(e.returning&&e.returning.length){let l=e.returning.map(u=>r.formatStringColumn("postgres",u)).join(", ");a+=` returning ${l}`;}return {sql:a,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}`;}return {sql:s,bindings:[]}}},om=new _i;var Oi=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:[]}}},nm=new Oi;var Ai=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},sm=new Ai;var xi=class{toSql(t){return {sql:`SELECT
|
|
126
|
+
ORDER BY column_id`,bindings:[]}}},yc=new Ks;var Qs=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 T(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 T(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 T(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},hc=new Qs;var ks=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=ce.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}},gc=new ks;var Ls=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:[]}}},bc=new Ls;var Ws=class{toSql(t){let e=t,r=new T(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}}},Tc=new Ws;var js=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,u)=>{let d=e.values[u];return d instanceof $?`${r.formatStringColumn("oracledb",l)} = ${d.rawValue}`:(s.push(d),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},wc=new js;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(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}},Nc=new Fs;var Us=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new T(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Sc=new Us;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}}},qc=new Vs;var Js=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"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 T(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Cc=new Js;var Hs=class{toSql(t){let e=t,r=new T(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}}},Rc=new Hs;var zs=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Mc=new zs;var Ys=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},_c=new Ys;var Gs=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Oc=new Gs;var Zs=class{toSql(t){let e=t,r=new T(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" ");s=s.replace(/\s*check\s*\(.*\)\s*$/i,"").trim();let 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:[]}}},Ac=new Zs;var Xs=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 T(this.model,"postgres"),s=[],a=[];for(let p of e.children){let{sql:c,bindings:m}=n.parse([p]);s.push(c.trim()),a.push(...m);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},xc=new Xs;var ei=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Dc=new ei;var ti=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},Ic=new ti;var ri=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},$c=new ri;var oi=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Pc=new oi;var ni=class{toSql(t){return {sql:"",bindings:[]}}},Ec=new ni;var si=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},vc=new si;var ii=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Bc=new ii;var ai=class{toSql(t){let e=t,r;return e.defaultValue instanceof $?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:[]}}},Kc=new ai;var li=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Qc=new li;var ui=class{toSql(t){return {sql:"",bindings:[]}}},kc=new ui;var di=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("postgres",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}else if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar(${a})`,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 a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${a}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let a=e.withTimezone?" with time zone":" without time zone",l=typeof e.precision=="number"?`(${e.precision})`:"",u=`${o} timestamp${l}${a}`.trimEnd();return e.autoCreate&&(u+=" default current_timestamp"),{sql:u,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 a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} text check (${o} in (${a}))`,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:[]}}}}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},Lc=new di;var ci=class{toSql(t){return {sql:"",bindings:[]}}},Wc=new ci;var mi=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",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("postgres",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof $?{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(u=>r.formatStringColumn("postgres",S(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("postgres",S(u))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},jc=new mi;var pi=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 T(this.model,"postgres"),s=[],a=[];for(let w of e.children){let{sql:q,bindings:M}=n.parse([w]);if(w.folder==="constraint"){let R=s.pop()??"",A=q;if(/not null/i.test(A)||/null/i.test(A)||/default/i.test(A)){let D=`${R} ${A}`.trim();D=D.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(D),a.push(...M);continue}s.push(R),s.push(A),a.push(...M);continue}s.push(q),a.push(...M);}for(let w of e.namedConstraints){let{sql:q,bindings:M}=n.parse([w]);s.push(q),a.push(...M);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.temporary&&d.push("TEMPORARY"),e.unlogged&&d.push("UNLOGGED");let p=[];if(e.postgresWith){let w=Object.entries(e.postgresWith).map(([q,M])=>`${q}=${M}`).join(", ");w&&p.push(`WITH (${w})`);}let c=e.tablespace?`TABLESPACE ${e.tablespace}`:"",m=d.length>0?`${d.join(" ")} `:"",g=p.length>0?` ${p.join(" ")}`:"",f=c?` ${c}`:"";return {sql:`${u}${m}${o} (${l})${g}${f}`,bindings:a}}},Fc=new pi;var fi=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode.table=="string")return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),n=r.getFromForWriteOperations("postgres",e.fromNode);if(e.returning&&e.returning.length){let s=e.returning.map(a=>r.formatStringColumn("postgres",a)).join(", ");n+=` returning ${s}`;}return {sql:n,bindings:[]}}},Uc=new fi;var yi=class{toSql(t){return {sql:"",bindings:[]}}},Vc=new yi;var hi=class{toSql(t){return {sql:`(${t.columns.map(o=>new y(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},Jc=new hi;var gi=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Hc=new gi;var bi=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},zc=new bi;var Ti=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 T(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Yc=new Ti;var wi=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},Gc=new wi;var Ni=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 N)&&!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}}},Zc=new Ni;var Si=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:[]}}},Xc=new Si;var qi=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},em=new qi;var Ci=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=[],u=[],d=e.currParamIndex;for(let c of e.records){let m=s.map(f=>c[f]),g=[];for(let f=0;f<s.length;f++){let b=m[f];b instanceof $?g.push(b.rawValue):(l.push(b),g.push(`$${d++}${this.formatTypeCast(b)}`));}u.push(`(${g.join(", ")})`);}let p=`${o} (${a}) values ${u.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(m=>r.formatStringColumn("postgres",m)).join(", ");p+=` returning ${c}`;}else p+=" returning *";return {sql:p,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},tm=new Ci;var Ri=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),u=`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"postgres");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},rm=new Ri;var Mi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},om=new Mi;var Hf={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},_i=class{toSql(t){let e=t,r=Hf[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},nm=new _i;var Oi=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},sm=new Oi;var Ai=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"){let a=`on conflict (${o}) do nothing`;if(e.returning&&e.returning.length){let l=e.returning.map(u=>r.formatStringColumn("postgres",u)).join(", ");a+=` returning ${l}`;}return {sql:a,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}`;}return {sql:s,bindings:[]}}},im=new Ai;var xi=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:[]}}},am=new xi;var Di=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},lm=new Di;var Ii=class{toSql(t){return {sql:`SELECT
|
|
127
127
|
con.conname AS name,
|
|
128
128
|
pg_get_constraintdef(con.oid) AS expression
|
|
129
129
|
FROM pg_constraint con
|
|
@@ -131,7 +131,7 @@ ORDER BY column_id`,bindings:[]}}},mc=new vs;var Bs=class{toSql(t){let e=t;if(e.
|
|
|
131
131
|
JOIN pg_namespace nsp ON nsp.oid = rel.relnamespace
|
|
132
132
|
WHERE con.contype = 'c'
|
|
133
133
|
AND rel.relname = '${t.table}'
|
|
134
|
-
AND nsp.nspname = current_schema()`,bindings:[]}}},
|
|
134
|
+
AND nsp.nspname = current_schema()`,bindings:[]}}},um=new Ii;var $i=class{toSql(t){return {sql:`SELECT
|
|
135
135
|
tc.constraint_name as name,
|
|
136
136
|
kcu.column_name as column_name,
|
|
137
137
|
ccu.table_name as referenced_table,
|
|
@@ -146,7 +146,7 @@ ORDER BY column_id`,bindings:[]}}},mc=new vs;var Bs=class{toSql(t){let e=t;if(e.
|
|
|
146
146
|
JOIN information_schema.referential_constraints rc
|
|
147
147
|
ON rc.constraint_name = tc.constraint_name AND rc.constraint_schema = tc.table_schema
|
|
148
148
|
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
|
|
149
|
-
ORDER BY kcu.ordinal_position`,bindings:[]}}},
|
|
149
|
+
ORDER BY kcu.ordinal_position`,bindings:[]}}},dm=new $i;var Pi=class{toSql(t){return {sql:`SELECT
|
|
150
150
|
i.relname as index_name,
|
|
151
151
|
a.attname as column_name,
|
|
152
152
|
ix.indisunique as is_unique
|
|
@@ -165,14 +165,14 @@ ORDER BY column_id`,bindings:[]}}},mc=new vs;var Bs=class{toSql(t){let e=t;if(e.
|
|
|
165
165
|
AND t.relname = '${t.table}'
|
|
166
166
|
AND t.relnamespace = n.oid
|
|
167
167
|
AND n.nspname = current_schema()
|
|
168
|
-
AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},
|
|
168
|
+
AND i.relname NOT LIKE 'pk_%'`,bindings:[]}}},cm=new Pi;var Ei=class{toSql(t){return {sql:`SELECT
|
|
169
169
|
tc.constraint_name as name,
|
|
170
170
|
kcu.column_name as column_name
|
|
171
171
|
FROM information_schema.table_constraints tc
|
|
172
172
|
JOIN information_schema.key_column_usage kcu
|
|
173
173
|
ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
|
|
174
174
|
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = current_schema() AND tc.table_name = '${t.table}'
|
|
175
|
-
ORDER BY kcu.ordinal_position`,bindings:[]}}},
|
|
175
|
+
ORDER BY kcu.ordinal_position`,bindings:[]}}},mm=new Ei;var vi=class{toSql(t){return {sql:`SELECT column_name,
|
|
176
176
|
data_type,
|
|
177
177
|
is_nullable,
|
|
178
178
|
column_default,
|
|
@@ -182,15 +182,15 @@ ORDER BY column_id`,bindings:[]}}},mc=new vs;var Bs=class{toSql(t){let e=t;if(e.
|
|
|
182
182
|
FROM information_schema.columns
|
|
183
183
|
WHERE table_schema = current_schema()
|
|
184
184
|
AND table_name = '${t.table}'
|
|
185
|
-
ORDER BY ordinal_position`,bindings:[]}}},dm=new $i;var Ei=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new T(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},cm=new Ei;var vi=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=ce.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toPostgres(false);return r?`${t}${r}`:t}buildExtractTextSql(t,e){if(e.isEmpty())return `${t}::text`;let r=e.toPostgres(true);return `${t}${r}`}buildArrayLengthSql(t,e){return `jsonb_array_length(${this.buildExtractSql(t,e)})`}buildObjectKeysSql(t,e){return `jsonb_object_keys(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},mm=new vi;var Bi=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:[]}}},pm=new Bi;var Qi=class{toSql(t){let e=t,r=new T(this.model,"postgres"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},fm=new Qi;var Ki=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((u,d)=>{let p=e.currParamIndex+d-n,c=e.values[d];return c instanceof P?(n++,`${r.formatStringColumn("postgres",u)} = ${c.rawValue}`):(s.push(c),`${r.formatStringColumn("postgres",u)} = $${p}${this.formatTypeCast(c)}`)}).join(", "),l=`${o} set ${a}`;if(e.returning&&e.returning.length){let u=e.returning.map(d=>r.formatStringColumn("postgres",d)).join(", ");l+=` returning ${u}`;}return {sql:l,bindings:s}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},ym=new Ki;var ki=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}},hm=new ki;var Li=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new T(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},gm=new Li;var Wi=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}}},bm=new Wi;var ji=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"postgres"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Tm=new ji;var Fi=class{toSql(t){let e=t,r=new T(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},wm=new Fi;var Ui=class{toSql(t){let e=t,r=new T(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Sm=new Ui;var Vi=class{toSql(t){return {sql:"",bindings:[]}}},Nm=new Vi;var Ji=class{toSql(t){return {sql:"",bindings:[]}}},qm=new Ji;var Hi=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 T(this.model,"sqlite"),s=[],a=[],l=false;for(let c of e.children){let{sql:m,bindings:g}=n.parse([c]);if(!(!m||!m.trim())){if(c.file==="add_column")s.push(m),l=true;else if(c.file==="add_constraint"&&l){let f=s.pop()??"",b=m.replace(/^\s*add\s+/i,"").trimStart();s.push(`${f} ${b}`);}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(m),l=false;}a.push(...g);}}let u=s.join(", "),d=e.ifExists?"if exists ":"";return u.trim()?{sql:`${d}${o} ${u}`,bindings:a}:{sql:"",bindings:[]}}},Cm=new Hi;var zi=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Rm=new zi;var Yi=class{toSql(t){return {sql:"",bindings:[]}}},Mm=new Yi;var Gi=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},_m=new Gi;var Zi=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Om=new Zi;var Xi=class{toSql(t){return {sql:"",bindings:[]}}},Am=new Xi;var ea=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},xm=new ea;var ta=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Dm=new ta;var ra=class{toSql(t){let e=t,r;return e.defaultValue instanceof P?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},Im=new ra;var oa=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},Pm=new oa;var na=class{toSql(t){return {sql:"",bindings:[]}}},$m=new na;var sa=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==="bigincrement")return {sql:`${o} integer primary key autoincrement`,bindings:[]};if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return e.autoIncrement?{sql:`${o} integer primary key autoincrement`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}if(n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"){let a=`${o} text`;return (n==="datetime"||n==="timestamp")&&e.autoCreate&&(a+=" default current_timestamp"),{sql:a,bindings:[]}}else {if(n==="boolean")return {sql:`${o} integer`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} text`,bindings:[]};if(n==="enum")return {sql:`${o} text`,bindings:[]};if(n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} ${n}`,bindings:[]}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},Em=new sa;var ia=class{toSql(t){return {sql:"",bindings:[]}}},vm=new ia;var aa=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 P?{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(u=>r.formatStringColumn("sqlite",N(u))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(u=>r.formatStringColumn("sqlite",N(u))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${o}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Bm=new aa;var la=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 T(this.model,"sqlite"),s=[],a=[];for(let f of e.children){let{sql:b,bindings:w}=n.parse([f]);if(f.folder==="constraint"){let q=s.pop()??"",M=b;if(/not null/i.test(M)||/null/i.test(M)||/default/i.test(M)||/primary key/i.test(M)){let R=`${q} ${M}`.trim();R=R.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(R),a.push(...w);continue}s.push(q),s.push(M),a.push(...w);continue}s.push(b),a.push(...w);}for(let f of e.namedConstraints){let{sql:b,bindings:w}=n.parse([f]);s.push(b),a.push(...w);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.sqliteTemporary&&d.push("TEMPORARY");let p=d.length>0?`${d.join(" ")} `:"",c=e.withoutRowId?" WITHOUT ROWID":"",m=e.strict?" STRICT":"";return {sql:`${u}${p}${o} (${l})${c}${m}`,bindings:a}}},Qm=new la;var ua=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:[]}}},Km=new ua;var da=class{toSql(t){return {sql:"distinct",bindings:[]}}},km=new da;var ca=class{toSql(t){return _.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Lm=new ca;var ma=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Wm=new ma;var pa=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},jm=new pa;var fa=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 T(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Fm=new fa;var ya=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},Um=new ya;var ha=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 S)&&!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}}},Vm=new ha;var ga=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:[]}}},Jm=new ga;var ba=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},Hm=new ba;var Ta=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(p=>r.formatStringColumn("sqlite",p)).join(", "),l=[],u=[];for(let p of e.records){let c=s.map(g=>p[g]),m=[];for(let g of c)g instanceof P?m.push(g.rawValue):(l.push(g),m.push("?"));u.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${u.join(", ")}`,bindings:l}}},zm=new Ta;var wa=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),u=`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"sqlite");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},Ym=new wa;var Sa=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},Gm=new Sa;var Na=class{toSql(t){return {sql:"",bindings:[]}}},Zm=new Na;var qa=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Xm=new qa;var Ca=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:[]}}},ep=new Ca;var Ra=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:[]}}},tp=new Ra;var Ma=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},rp=new Ma;var _a=class{toSql(t){return {sql:"SELECT 1 WHERE 0",bindings:[]}}},op=new _a;var Oa=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},np=new Oa;var Aa=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},sp=new Aa;var xa=class{toSql(t){return {sql:`SELECT
|
|
185
|
+
ORDER BY ordinal_position`,bindings:[]}}},pm=new vi;var Bi=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new T(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},fm=new Bi;var Ki=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=ce.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}},ym=new Ki;var Qi=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:[]}}},hm=new Qi;var ki=class{toSql(t){let e=t,r=new T(this.model,"postgres"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},gm=new ki;var Li=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((u,d)=>{let p=e.currParamIndex+d-n,c=e.values[d];return c instanceof $?(n++,`${r.formatStringColumn("postgres",u)} = ${c.rawValue}`):(s.push(c),`${r.formatStringColumn("postgres",u)} = $${p}${this.formatTypeCast(c)}`)}).join(", "),l=`${o} set ${a}`;if(e.returning&&e.returning.length){let u=e.returning.map(d=>r.formatStringColumn("postgres",d)).join(", ");l+=` returning ${u}`;}return {sql:l,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 Li;var Wi=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}},Tm=new Wi;var ji=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new T(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},wm=new ji;var Fi=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}}},Nm=new Fi;var Ui=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"postgres"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Sm=new Ui;var Vi=class{toSql(t){let e=t,r=new T(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},qm=new Vi;var Ji=class{toSql(t){let e=t,r=new T(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Cm=new Ji;var Hi=class{toSql(t){return {sql:"",bindings:[]}}},Rm=new Hi;var zi=class{toSql(t){return {sql:"",bindings:[]}}},Mm=new zi;var Yi=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 T(this.model,"sqlite"),s=[],a=[],l=false;for(let c of e.children){let{sql:m,bindings:g}=n.parse([c]);if(!(!m||!m.trim())){if(c.file==="add_column")s.push(m),l=true;else if(c.file==="add_constraint"&&l){let f=s.pop()??"",b=m.replace(/^\s*add\s+/i,"").trimStart();s.push(`${f} ${b}`);}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(m),l=false;}a.push(...g);}}let u=s.join(", "),d=e.ifExists?"if exists ":"";return u.trim()?{sql:`${d}${o} ${u}`,bindings:a}:{sql:"",bindings:[]}}},_m=new Yi;var Gi=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},Om=new Gi;var Zi=class{toSql(t){return {sql:"",bindings:[]}}},Am=new Zi;var Xi=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},xm=new Xi;var ea=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},Dm=new ea;var ta=class{toSql(t){return {sql:"",bindings:[]}}},Im=new ta;var ra=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},$m=new ra;var oa=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},Pm=new oa;var na=class{toSql(t){let e=t,r;return e.defaultValue instanceof $?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:[]}}},Em=new na;var sa=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},vm=new sa;var ia=class{toSql(t){return {sql:"",bindings:[]}}},Bm=new ia;var aa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new y(this.model).formatStringColumn("sqlite",S(e.column)),n=e.dataType.toLowerCase();if(n==="bigincrement")return {sql:`${o} integer primary key autoincrement`,bindings:[]};if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return e.autoIncrement?{sql:`${o} integer primary key autoincrement`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}if(n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"){let a=`${o} text`;return (n==="datetime"||n==="timestamp")&&e.autoCreate&&(a+=" default current_timestamp"),{sql:a,bindings:[]}}else {if(n==="boolean")return {sql:`${o} integer`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} text`,bindings:[]};if(n==="enum")return {sql:`${o} text`,bindings:[]};if(n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} ${n}`,bindings:[]}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},Km=new aa;var la=class{toSql(t){return {sql:"",bindings:[]}}},Qm=new la;var ua=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",S(s))).join(", ");return e.constraintName?{sql:`${o}unique (${n})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let n=e.defaultValue;return n instanceof $?{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(u=>r.formatStringColumn("sqlite",S(u))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(u=>r.formatStringColumn("sqlite",S(u))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${o}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},km=new ua;var da=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 T(this.model,"sqlite"),s=[],a=[];for(let f of e.children){let{sql:b,bindings:w}=n.parse([f]);if(f.folder==="constraint"){let q=s.pop()??"",M=b;if(/not null/i.test(M)||/null/i.test(M)||/default/i.test(M)||/primary key/i.test(M)){let R=`${q} ${M}`.trim();R=R.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(R),a.push(...w);continue}s.push(q),s.push(M),a.push(...w);continue}s.push(b),a.push(...w);}for(let f of e.namedConstraints){let{sql:b,bindings:w}=n.parse([f]);s.push(b),a.push(...w);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.sqliteTemporary&&d.push("TEMPORARY");let p=d.length>0?`${d.join(" ")} `:"",c=e.withoutRowId?" WITHOUT ROWID":"",m=e.strict?" STRICT":"";return {sql:`${u}${p}${o} (${l})${c}${m}`,bindings:a}}},Lm=new da;var ca=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:[]}}},Wm=new ca;var ma=class{toSql(t){return {sql:"distinct",bindings:[]}}},jm=new ma;var pa=class{toSql(t){return _.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Fm=new pa;var fa=class{toSql(t){let e=t,o=new y(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Um=new fa;var ya=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},Vm=new ya;var ha=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 T(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Jm=new ha;var ga=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},Hm=new ga;var ba=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 N)&&!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}}},zm=new ba;var Ta=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:[]}}},Ym=new Ta;var wa=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},Gm=new wa;var Na=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(p=>r.formatStringColumn("sqlite",p)).join(", "),l=[],u=[];for(let p of e.records){let c=s.map(g=>p[g]),m=[];for(let g of c)g instanceof $?m.push(g.rawValue):(l.push(g),m.push("?"));u.push(`(${m.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${u.join(", ")}`,bindings:l}}},Zm=new Na;var Sa=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),u=`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let p=new T(this.model,"sqlite");for(let c of e.additionalConditions){let m=p.parse([c]);if(m.sql){let g=m.sql.replace(/^where\s+/i,"");u+=` and ${g}`,d.push(...m.bindings);}}}return {sql:u,bindings:d}}},Xm=new Sa;var qa=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},ep=new qa;var Ca=class{toSql(t){return {sql:"",bindings:[]}}},tp=new Ca;var Ra=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},rp=new Ra;var Ma=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:[]}}},op=new Ma;var _a=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:[]}}},np=new _a;var Oa=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},sp=new Oa;var Aa=class{toSql(t){return {sql:"SELECT 1 WHERE 0",bindings:[]}}},ip=new Aa;var xa=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},ap=new xa;var Da=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},lp=new Da;var Ia=class{toSql(t){return {sql:`SELECT
|
|
186
186
|
'PRIMARY' as name,
|
|
187
187
|
name as column_name
|
|
188
188
|
FROM pragma_table_info('${t.table}')
|
|
189
189
|
WHERE pk > 0
|
|
190
|
-
ORDER BY pk`,bindings:[]}}},ip=new xa;var Da=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},ap=new Da;var Ia=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new T(this.model,"sqlite").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},lp=new Ia;var Pa=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=ce.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}},up=new Pa;var $a=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:[]}}},dp=new $a;var Ea=class{toSql(t){let e=t,r=new T(this.model,"sqlite"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},cp=new Ea;var va=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 u=e.values[l];return u instanceof P?`${r.formatStringColumn("sqlite",a)} = ${u.rawValue}`:(n.push(u),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},mp=new va;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}},pp=new Ba;var Qa=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new T(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},fp=new Qa;var Ka=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}}},yp=new Ka;var ka=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"sqlite"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},hp=new ka;var La=class{toSql(t){let e=t,r=new T(this.model,"sqlite"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},gp=new La;var bp={mssql:{alter_table:{add_column:Ml,add_constraint:_l,add_primary_key:Ol,alter_column_type:Al,alter_table:xl,drop_column:Dl,drop_constraint:Il,drop_default:Pl,drop_not_null:Bl,drop_primary_key:Ql,rename_column:Kl,rename_table:kl,set_default:Ll,set_not_null:Wl,set_table_options:jl},column:{column_type:Fl},constraint:{after:Ul,constraint:Vl},create_table:{create_table:Jl},delete:{delete:Hl},distinct:{distinct:zl,distinct_on:Yl},drop_table:{drop_table:Gl},extension:{create_extension:Zl},from:{from:Xl},group_by:{group_by:eu},having:{having:tu},index_op:{create_index:ru,drop_index:ou},insert:{insert:nu},join:{join:su},limit:{limit:iu},lock:{lock:au},offset:{offset:lu},on_duplicate:{on_duplicate:uu},order_by:{order_by:du},raw:{raw:cu},schema:{check_constraint_info:mu,foreign_key_info:pu,index_info:fu,primary_key_info:yu,table_info:hu},select:{select:gu,select_json:bu},truncate:{truncate:Tu},union:{union:wu},update:{update:Su},where:{where:Nu,where_group:qu,where_json:Cu,where_subquery:Ru},with:{with:Mu}},mysql:{alter_table:{add_column:_u,add_constraint:Ou,add_primary_key:Au,alter_column_type:xu,alter_table:Du,drop_column:Iu,drop_constraint:Pu,drop_default:$u,drop_not_null:Eu,drop_primary_key:vu,rename_column:Bu,rename_table:Qu,set_default:Ku,set_not_null:ku,set_table_options:Lu},column:{column_type:Wu},constraint:{after:ju,constraint:Fu},create_table:{create_table:Uu},delete:{delete:Vu},distinct:{distinct:Ju,distinct_on:Hu},drop_table:{drop_table:zu},extension:{create_extension:Yu},from:{from:Gu},group_by:{group_by:Zu},having:{having:Xu},index_op:{create_index:ed,drop_index:td},insert:{insert:rd},join:{join:od},limit:{limit:nd},lock:{lock:sd},offset:{offset:id},on_duplicate:{on_duplicate:ad},order_by:{order_by:ld},raw:{raw:ud},schema:{check_constraint_info:dd,foreign_key_info:cd,index_info:md,primary_key_info:pd,table_info:fd},select:{select:yd,select_json:hd},truncate:{truncate:gd},union:{union:bd},update:{update:Td},where:{where:wd,where_group:Sd,where_json:Nd,where_subquery:qd},with:{with:Cd}},oracledb:{alter_table:{add_column:Rd,add_constraint:Md,add_primary_key:_d,alter_column_type:Od,alter_table:Ad,drop_column:xd,drop_constraint:Dd,drop_default:Id,drop_not_null:Pd,drop_primary_key:$d,rename_column:Ed,rename_table:vd,set_default:Bd,set_not_null:Qd,set_table_options:Kd},column:{column_type:kd},constraint:{after:Ld,constraint:Wd},create_table:{create_table:jd},delete:{delete:Fd},distinct:{distinct:Ud,distinct_on:Vd},drop_table:{drop_table:Jd},extension:{create_extension:Hd},from:{from:zd},group_by:{group_by:Yd},having:{having:Gd},index_op:{create_index:Zd,drop_index:Xd},insert:{insert:ec},join:{join:tc},limit:{limit:rc},lock:{lock:oc},offset:{offset:nc},on_duplicate:{on_duplicate:sc},order_by:{order_by:ic},raw:{raw:ac},schema:{check_constraint_info:lc,foreign_key_info:uc,index_info:dc,primary_key_info:cc,table_info:mc},select:{select:pc,select_json:fc},truncate:{truncate:yc},union:{union:hc},update:{update:gc},where:{where:bc,where_group:Tc,where_json:wc,where_subquery:Sc},with:{with:Nc}},postgres:{alter_table:{add_column:qc,add_constraint:Cc,add_primary_key:Rc,alter_column_type:Mc,alter_table:_c,drop_column:Oc,drop_constraint:Ac,drop_default:xc,drop_not_null:Dc,drop_primary_key:Ic,rename_column:Pc,rename_table:$c,set_default:Ec,set_not_null:vc,set_table_options:Bc},column:{column_type:Qc},constraint:{after:Kc,constraint:kc},create_table:{create_table:Lc},delete:{delete:Wc},distinct:{distinct:jc,distinct_on:Fc},drop_table:{drop_table:Uc},extension:{create_extension:Vc},from:{from:Jc},group_by:{group_by:Hc},having:{having:zc},index_op:{create_index:Yc,drop_index:Gc},insert:{insert:Zc},join:{join:Xc},limit:{limit:em},lock:{lock:tm},offset:{offset:rm},on_duplicate:{on_duplicate:om},order_by:{order_by:nm},raw:{raw:sm},schema:{check_constraint_info:im,foreign_key_info:am,index_info:lm,primary_key_info:um,table_info:dm},select:{select:cm,select_json:mm},transaction:{},truncate:{truncate:pm},union:{union:fm},update:{update:ym},where:{where:hm,where_group:gm,where_json:bm,where_subquery:Tm},with:{with:wm}},sqlite:{alter_table:{add_column:Sm,add_constraint:Nm,alter_column_type:qm,alter_table:Cm,drop_column:Rm,drop_constraint:Mm,drop_default:_m,drop_not_null:Om,drop_primary_key:Am,rename_column:xm,rename_table:Dm,set_default:Im,set_not_null:Pm,set_table_options:$m},column:{column_type:Em},constraint:{after:vm,constraint:Bm},create_table:{create_table:Qm},delete:{delete:Km},distinct:{distinct:km,distinct_on:Lm},drop_table:{drop_table:Wm},extension:{create_extension:jm},from:{from:Fm},group_by:{group_by:Um},having:{having:Vm},index_op:{create_index:Jm,drop_index:Hm},insert:{insert:zm},join:{join:Ym},limit:{limit:Gm},lock:{lock:Zm},offset:{offset:Xm},on_duplicate:{on_duplicate:ep},order_by:{order_by:tp},raw:{raw:rp},schema:{check_constraint_info:op,foreign_key_info:np,index_info:sp,primary_key_info:ip,table_info:ap},select:{select:lp,select_json:up},transaction:{},truncate:{truncate:dp},union:{union:cp},update:{update:mp},where:{where:pp,where_group:fp,where_json:yp,where_subquery:hp},with:{with:gp}}};var T=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(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"),u=l.some(R=>R.folder==="offset"),d=l.some(R=>R.folder==="order_by"),p=l.find(R=>R.folder==="limit"),c=l.find(R=>R.folder==="offset"),m=this.dbType==="mssql"&&p&&!u&&!d,g=this.dbType==="mssql"&&!m&&(p||c),f=this.dbType==="oracledb"&&(p||c),b=[],w=[],q=null;m&&p&&w.push(p.limit);for(let R=0;R<l.length;R++){let A=l[R];if(m&&A.folder==="limit"||g&&(A.folder==="limit"||A.folder==="offset")||f&&(A.folder==="limit"||A.folder==="offset"))continue;A.currParamIndex=e+w.length;let D=bp[this.mapCommonDbType(this.dbType)][A.folder][A.file];if(!D)throw new Error(`Interpreter not found for ${this.dbType} ${A.keyword}`);D.model=this.model;let C=D.toSql(A);if(!C.sql||!C.sql.trim().length)continue;let v=l[R+1],$=!v||v.keyword!==A.keyword?"":v.chainsWith;if(A.folder==="lock"||A.folder==="on_duplicate"||A.folder==="schema"){b.push(`${C.sql}${$}`),w.push(...C.bindings),q=A.keyword;continue}if(q!==A.keyword||A.canKeywordBeSeenMultipleTimes){if(r)b.push(`${C.sql}${$}`);else {let Z=A.keyword;if(A.folder==="with"&&this.dbType!=="mssql"){let ee=R,qe=false;for(;ee<l.length&&l[ee].keyword===A.keyword;){let Ae=l[ee];if(Ae.folder==="with"&&Ae.clause==="recursive"){qe=true;break}ee++;}qe&&(Z=`${Z} recursive`);}if(Z==="select"){let ee=m?`top (@${e}) `:"";if(o){let qe=Array.isArray(o.columns)?o.columns.join(", "):"";b.push(`select ${ee}distinct on (${qe}) ${C.sql}${$}`);}else n?b.push(`select ${ee}distinct ${C.sql}${$}`):b.push(`select ${ee}${C.sql}${$}`);}else Z==="from"&&a?b.push(`${Z} ${C.sql}${a}${$}`):b.push(`${Z} ${C.sql}${$}`);}q=A.keyword;}else b.push(`${C.sql}${$}`);w.push(...C.bindings);}if(g){d||b.push("order by (select null)");let R=c?.offset??0;w.push(R);let D=`offset @${e+w.length-1} rows`;if(p){w.push(p.limit);let C=e+w.length-1;D+=` fetch next @${C} rows only`;}b.push(D);}if(f){d||b.push("order by null");let R=c?.offset??0;w.push(R);let D=`offset :${e+w.length-1} rows`;if(p){w.push(p.limit);let C=e+w.length-1;D+=` fetch next :${C} rows only`;}b.push(D);}return {sql:b.join(" "),bindings:w}}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 Vf=i=>{if(i==null||typeof i!="object"||i instanceof Date)return false;if(Array.isArray(i))return true;let t=Object.getPrototypeOf(i);return t===Object.prototype||t===null},y=class{constructor(t){this.model=t;this.modelColumnsMap=typeof t.getColumnsByName=="function"?t.getColumnsByName():new Map;let e=[],r=[];for(let o of this.modelColumnsMap.values())(o.prepare||o.autoUpdate)&&e.push(o),o.autoUpdate&&r.push(o);this.autoInsertColumns=e,this.autoUpdateColumns=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??V(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??V(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 d=0;d<t.length;d++){let p=t[d],c=e[d];p!=="*"&&(o.push(p),n.push(c));}let s=new Set(o),a=null;for(let d=0;d<o.length;d++){let p=o[d],c=n[d],m=this.modelColumnsMap.get(p);if(m){if(m.prepare){let g=r==="insert"?m.prepare(c):m.prepare(c)??c;g!==null&&typeof g?.then=="function"?(a||(a=[]),a.push({index:d,promise:g})):n[d]=g;}}else Vf(c)&&(n[d]=JSON.stringify(c));}if(a){let d=await Promise.all(a.map(p=>p.promise));for(let p=0;p<a.length;p++)n[a[p].index]=d[p];}let l=this.model.primaryKey,u=r==="insert"?this.autoInsertColumns:this.autoUpdateColumns;for(let d of u){let p=d.columnName;if(s.has(p)||r==="insert"&&p===l&&!d.prepare)continue;o.push(p);let c=d.prepare?await d.prepare(void 0):void 0;n.push(c??void 0);}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new T(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var rt=class extends S{constructor(e,r=false,o){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e,this.returning=o;}};var U=class extends S{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var z=class extends S{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 he=class extends S{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 _e=class extends S{constructor(e,r=[],o=[],n=false,s){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o,this.returning=s;}};var Tp;Tp=Symbol.toStringTag;var G=class{constructor(t,e,r,o){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=o;this[Tp]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}toSql(){return this.toSqlFn()}unWrap(){return this.unWrapFn()}};var Jf=async(i,t,e,r,o,n=false)=>{let s=Object.create(t.prototype),a=null;for(let l of Object.keys(i)){let u=i[l],d=r.get(l)?.columnName??l,p=e.has(d),c=n?true:o?o.has(d):true;if(p){if(!c)continue;if(u===null){s[d]=null;continue}let m=e.get(d);if(m?.serialize){let g=m.serialize(u);g!==null&&typeof g?.then=="function"?(a||(a=[]),a.push({key:d,promise:g})):s[d]=g;continue}s[d]=u;continue}(!n||o&&o.has(d))&&(s[d]=u);}if(a){let l=await Promise.all(a.map(u=>u.promise));for(let u=0;u<a.length;u++)s[a[u].key]=l[u];}if(o)for(let l of o)l in s||(s[l]=null);return s},Oe=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),o=t.getColumnsByDatabaseName(),n=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let m=u.match(/\s+as\s+(.+)$/i);m&&s.push(m[1].trim());continue}let p=u;if(p.includes(".")&&(p=p.split(".").pop()),p==="*")continue;let c=r.get(p)?.columnName??p;s.push(c);}let a=s.length?new Set(s):null,l=await Promise.all(i.map(u=>Jf(u,t,r,o,a,n)));return l.length===1?l[0]:l};var k=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Hf=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,zf=/^\d{4}-\d{2}-\d{2}$/,Wa=i=>typeof i!="string"?i:Hf.test(i)?new Date(i.replace(" ","T")+"Z"):zf.test(i)?new Date(i+"T00:00:00Z"):i,Yf=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);}}),wp=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Yf(r):t[e]=r;}return t};var Wt=class extends 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:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(u=>{r=true,this.emit("error",u);}).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);});}},Sp=(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((u,d)=>{n.run(i,t,function(p){p&&d(p),u(this.changes);});});if(r.mode==="fetch")return new Promise((u,d)=>{n.all(i,t,(p,c)=>{p&&d(p),(!c||!c.length)&&u([]),u(c);});});let s=r?.typeofModel;if(!s)return new Promise((u,d)=>{n.run(i,t,function(p){p?d(new Error(p.message)):u(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((p,c)=>{n.run(i,t,function(m){if(m)return c(m);let g=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){p([g]);return}let f=g?.[a]||this.lastID;if(!f)return c(new h("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let b=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(b,[f],(w,q)=>{if(w)return c(w);p([q]);});});});if(!Array.isArray(r.models))throw new h("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let u=r.models;if(!a)return new Promise((p,c)=>{n.run(i,t,function(m){if(m)return c(m);p(u);});});let d=[];return new Promise(async(p,c)=>{try{let m=u.map(async g=>{let f=new y(s),{columns:b,values:w}=await f.prepareColumns(Object.keys(g),Object.values(g),"insert"),q=Object.fromEntries(b.map((D,C)=>[D,w[C]])),M=new T(s,e.getDbType()),{sql:R,bindings:A}=M.parse([new z(new U(s.table),[q])]);return new Promise((D,C)=>{n.run(R,A,function(v){if(v)return C(v);let re=g[a]||this.lastID;if(!re)return C(new h("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let $=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get($,[re],(Z,ee)=>{if(Z)return C(Z);D(ee);});});})});d=await Promise.all(m),p(d);}catch(m){c(m);}})}return new Promise((u,d)=>{n.run(i,t,function(p){p?d(new Error(p.message)):u(this.changes);});})};var H=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||oe(i,e.logs,t,e.inputDetails.queryFormatOptions,r),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await ht(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),u=0,d=i.replace(/\?/g,()=>`$${++u}`),p=await ht(()=>l.query(d,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let c=await ht(()=>Sp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(c)?c:[c]:c;case "mssql":let m=e.getPool(),g=e.sqlConnection?e.sqlConnection.request():m.request();t.forEach((A,D)=>{g.input(`p${D}`,A);});let f=0,b=i.replace(/\?|@(\d+)/g,()=>`@p${f++}`),w=await ht(()=>g.query(b),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?w.rowsAffected[0]:o==="raw"?w:w.recordset;case "oracledb":let q=4002,M=null,R=!!e.sqlConnection;try{M=e.sqlConnection?e.sqlConnection:await e.getConnection();let A=t.map(Wa),D=0,C=i.replace(/\?/g,()=>`:${++D}`),v=await ht(()=>M.execute(C,A,{outFormat:q,autoCommit:!R}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?v.rowsAffected:o==="raw"?v:await Promise.all(v.rows?.map(async $=>{let Z=await wp($),ee={};for(let qe in Z)ee[qe.toLowerCase()]=Z[qe];return ee})??[])}finally{M&&!R&&await M.close();}default:throw new h("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},Ft=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 PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),p=0,c=false,m=false,g=()=>{try{a.release();}catch{}};return d.on("data",f=>{if(o.onData){p++,Promise.resolve(o.onData(l,f)).then(()=>{p--,c&&p===0&&!m&&(g(),l.end());}).catch(b=>{m=true,g(),l.destroy(b);});return}l.write(f);}),d.on("end",()=>{c=true,p===0&&!m&&(g(),l.end());}),d.on("error",f=>{m=true,g(),l.destroy(f);}),l.on("close",()=>{g();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new k("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,p=i.replace(/\?/g,()=>`$${++d}`),c=new l.default(p,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),m=a.query(c),g=0,f=false,b=false,w=q=>{try{a.release(q);}catch{}};return m.on("data",q=>{if(o.onData){g++,Promise.resolve(o.onData(u,q)).then(()=>{g--,f&&g===0&&!b&&(w(),u.end());}).catch(M=>{b=true,w(M),u.destroy(M);});return}u.write(q);}),m.on("end",()=>{f=true,g===0&&!b&&(w(),u.end());}),m.on("error",q=>{b=true,w(q),u.destroy(q);}),u}case "sqlite":{let s=e.sqlConnection??e.getPool();return new Wt(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((g,f)=>{l.input(`p${f}`,g);});let u=0,d=i.replace(/\?|@(\d+)/g,()=>`@p${u++}`),p=0,c=false,m=false;return l.on("row",g=>{if(!m){if(o.onData){p++,Promise.resolve(o.onData(a,g)).then(()=>{p--,c&&p===0&&!m&&a.end();}).catch(f=>{m=true,a.destroy(f);});return}a.write(g);}}),l.on("error",g=>{m=true,a.destroy(g);}),l.on("done",()=>{c=true,p===0&&!m&&a.end();}),l.query(d),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=4002,d=0,p=i.replace(/\?/g,()=>`:${++d}`),c=t.map(Wa),m=a.queryStream(p,c,{outFormat:u}),g=0,f=false,b=false,w=async()=>{try{await a.close();}catch{}};return m.on("data",q=>{if(b)return;let M={};for(let R in q)M[R.toLowerCase()]=q[R];if(o.onData){g++,Promise.resolve(o.onData(l,M)).then(()=>{g--,f&&g===0&&!b&&(w(),l.end());}).catch(R=>{b=true,w(),l.destroy(R);});return}l.write(M);}),m.on("end",()=>{f=true,g===0&&!b&&(w(),l.end());}),m.on("error",q=>{b=true,w(),l.destroy(q);}),l}default:throw new h("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function ht(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,vl(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}function Np(){return {}}var Pe=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Np(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new T(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new h(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new h(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(u=>[u,t[u]])),o=!e.returning||e.returning.length===0,n=new z(new U(this.model.table),[r],e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new G(s,a,l,async()=>{e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:u,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),p={};u.forEach((q,M)=>{let R=d[M];p[q]=R,t[q]??(t[q]=R);});let c=!e.returning||e.returning.length===0,{sql:m,bindings:g}=this.astParser.parse([new z(new U(this.model.table),[p],e.returning,c)]),f=await H(m,g,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(f,[t],"one",e.returning);let b=f[0];return b?(await this.model.afterFetch?.([b]),await Oe([b],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(u=>Object.fromEntries(Object.keys(u).map(d=>[d,u[d]]))),o=!e.returning||e.returning.length===0,n=new z(new U(this.model.table),r,e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new G(s,a,l,async()=>{if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let b=this.model.primaryKey,w=Object.keys(t[0]||{});if(b&&!w.includes(b))return this.handleOracleIdentityInsert(t,e)}let u=new Array(t.length);await Promise.all(t.map(async(b,w)=>{let{columns:q,values:M}=await this.interpreterUtils.prepareColumns(Object.keys(b),Object.values(b),"insert"),R={};q.forEach((A,D)=>{let C=M[D];R[A]=C,b[A]??(b[A]=C);}),u[w]=R;}));let d=!e.returning||e.returning.length===0,{sql:p,bindings:c}=this.astParser.parse([new z(new U(this.model.table),u,e.returning,d)]),m=await H(p,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(m,t,"many",e.returning)||[];let g=m;return g.length?(await this.model.afterFetch?.(g),await Oe(g,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(m=>[m,c[m]]))),s=new z(new U(this.model.table),n,void 0,true),a=o.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0;new he(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",a);let u=()=>{let c=this.astParser.parse([s]);return {sql:c.sql,bindings:c.bindings}},d=()=>{let c=this.astParser.parse([s]);return {sql:Xe(this.sqlDataSource,c.sql),bindings:c.bindings}},p=()=>{let{sql:c,bindings:m}=d();return Ge(c,m)};return new G(u,d,p,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async A=>{let{columns:D,values:C}=await this.interpreterUtils.prepareColumns(Object.keys(A),Object.values(A),"insert"),v=Object.fromEntries(D.map((re,$)=>[re,C[$]]));c.push(v);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let m=!o.returning||o.returning.length===0,g=!m&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0,{sql:f,bindings:b}=this.astParser.parse([new z(new U(this.model.table),c,void 0,true),new he(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",g)]),w=await H(f,b,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(m)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(w.length<r.length&&!(o.updateOnConflict??true)){let C=t[0],v=r.map($=>$[C]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(C,v).many()}let A=w;return await this.model.afterFetch?.(A),await Oe(A,this.model,o.returning)||[]}let q=t[0],M=r.map(A=>A[q]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(q,M).many()})}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=D=>this.interpreterUtils.formatStringColumn("mssql",D),u=[],d=t.map(D=>`select ${s.map(v=>(u.push(D[v]),`@${u.length}`)).join(", ")}`),p=s.map(l).join(", "),c=d.join(" union all "),m=e.map(D=>`target.${l(D)} = source.${l(D)}`).join(" and "),g=r.filter(D=>!e.includes(D)).map(D=>`target.${l(D)} = source.${l(D)}`).join(", "),f=s.map(l).join(", "),b=s.map(D=>`source.${l(D)}`).join(", "),w=o.returning&&o.returning.length?o.returning.map(D=>`inserted.${l(D)}`).join(", "):s.map(D=>`inserted.${l(D)}`).join(", "),M=(o.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",R=`merge into ${a} as target using (${c}) as source (${p}) on ${m} ${M} when not matched then insert (${f}) values (${b}) output ${w};`,A=await H(R,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});if(A.length===0&&!(o.updateOnConflict??true)){let D=e[0],C=n.map(re=>re[D]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(D,C).many()}return A}async updateRecord(t,e,r){let o=new Set(this.model.getColumns().map(g=>g.columnName)),n=Object.keys(e).filter(g=>o.has(g)),s=n.map(g=>e[g]),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(n,s,"update"),{primaryKey:u}=this.model;if(!u)throw new h(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let{sql:p,bindings:c}=this.astParser.parse([new _e(new U(this.model.table),a,l),new x(u,"and",false,"=",t)]);if(await H(p,c,this.sqlDataSource,this.sqlType,"affectedRows"),!r?.returning||r.returning.length===0)return;let m=await this.findOneByPrimaryKey(t,r.returning);if(!m)throw new h(this.model.name+"::updateRecord","ROW_NOT_FOUND");return m}async deleteRecord(t){if(!this.model.primaryKey)throw new h(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new x(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:o}=this.astParser.parse([new rt(new U(this.model.table)),e]);await H(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new $e(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await Oe([a],this.model):null}return await Oe(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((m,g)=>{let f=a[g];l[m]=f,n[m]??(n[m]=f);});let{sql:u,bindings:d}=this.astParser.parse([new z(new U(this.model.table),[l],e.returning)]);await H(u,d,this.sqlDataSource,this.sqlType,"rows");let p=this.query().select(...e.returning||["*"]);for(let[m,g]of Object.entries(l))g!=null&&m!==o&&p.where(m,"=",g);o&&p.orderBy(o,"desc");let c=await p.one({ignoreHooks:["beforeFetch"]});if(c){let m=c;o&&m[o]&&(n[o]=m[o]),r.push(c);}else r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of n)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;o?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;o?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var gt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Sl(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 h("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Ut(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 qp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var ot=i=>typeof i=="number"?i:parseFloat(i);var Vt=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ge=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var nt=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Jt=class extends S{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var be=class extends S{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 Ht=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var Te=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var bt=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var zt=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var st=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Yt=class extends S{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Gt=class extends S{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Zt=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var We=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var B=class extends S{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false,this.unsigned=o.unsigned,this.zerofill=o.zerofill;}};var J=class extends S{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var Xt=class extends S{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var er=class extends S{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 tr=class extends S{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 rr=class extends S{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 or=class extends S{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 Tt=class extends S{constructor(e,r=false,o=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=o;}};var je=class extends S{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var it=class extends S{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 me=class extends S{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 at=class extends S{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var Fe=class extends S{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 nr=class extends S{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var sr=class extends S{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Ee=class extends S{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 ae=class extends S{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var wt=class extends S{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 ir=class extends S{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var ar=class extends S{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var St=class extends S{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 ur=class ur{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs,typeof t.getColumns=="function"?(this.modelColumns=t.getColumns(),this.modelColumnsMap=t.getColumnsByName?.()??new Map(this.modelColumns.map(r=>[r.columnName,r]))):(this.modelColumns=[],this.modelColumnsMap=ur.EMPTY_MAP);}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new wt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new wt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new St(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new St(t,"asc",true)),this}limit(t){return typeof t!="number"&&_.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new ir(t),this}offset(t){return typeof t!="number"&&_.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new ar(t),this}};ur.EMPTY_MAP=new Map;var lr=ur;var Ue=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",false,"in",e)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",false,"in",e)),this):(this.whereNodes.push(new x("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",true,"in",e)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",true,"in",e)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new x(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new x(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new x(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new x(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new x(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new x(t,"or",true,"=",e??[],true)),this}};var dr=class extends lr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ae(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ae(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ae(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ae(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ae(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ae(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var cr=class extends dr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=V(s,this.model.databaseCaseConvention);this.selectNodes.push(new me(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=V(o,this.model.databaseCaseConvention);this.selectNodes.push(new me(n));}),this}selectRaw(e){return this.selectNodes.push(new me(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":V(r,this.model.databaseCaseConvention);return this.selectNodes.push(new me(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new U(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}table(e){return this.fromNode=new U(e),this}distinct(){return this.distinctNode=new nr,this}distinctOn(...e){return this.distinctOnNode=new sr(e),this}selectJson(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Ee(e,"",r,"raw",true)),this}};var mr=class extends cr{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 Q&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||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 Q&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"and",false,n,new P(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"or",false,n,new P(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof Q&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 x(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",false,"in",r)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",false,"in",r)),this):(this.whereNodes.push(new x("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 x(e,"and",true,"in",r)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",true,"in",r)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new x(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new x(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new x(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new x(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 x(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 x(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new x(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new x(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 Fe(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 Fe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Fe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Fe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof Q)return e;let r=new Q(this.model,this.sqlDataSource),o=e(r);return o!=null&&"extractQueryNodes"in o?o:r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new ye(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new ye(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new Q(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new Q(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"or");return this.whereNodes.push(o),this}};var pr=class extends mr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new ie(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new ie(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new ie(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new ie(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new ie(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new ie(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new ie(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new ie(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new ie(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new ie(t,"or",false,"raw",e)),this}};var Q=class i extends pr{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new T(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new y(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource),s=r(n),a=s!=null&&"extractQueryNodes"in s?s:n;return this.selectNodes.push(new me(a.extractQueryNodes(),o)),this}return this.selectNodes.push(new me(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>H(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new h("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await Ft(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let[s,a]=await this.executePaginateQueries(()=>this.many(),()=>n.getCount()),l=s[s.length-1],u=l?l[r.discriminator]:null;return [{paginationMetadata:qp(e,a),data:s},{key:r.discriminator,value:u}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new Tt("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Tt("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new je(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new je(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&_.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:Ut(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new h("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource),n=e(o),a=(n!=null&&"extractQueryNodes"in n?n:o).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new it("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new it("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new h("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new it("materialized",e,s.extractQueryNodes())),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new z(this.fromNode,[o],r,n),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((m,g)=>[m,a[g]]));this.insertNode=new z(this.fromNode,[l],r,n);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),p=await this.getSqlDataSource("write"),c=await H(u,d,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new z(this.fromNode,o,r,n),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async p=>{let{columns:c,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert");return Object.fromEntries(c.map((g,f)=>[g,m[f]]))}));this.insertNode=new z(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await H(a,l,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return d})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new z(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new he(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(l.map((f,b)=>[f,u[b]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:p,bindings:c}=this.astParser.parse([new z(new U(this.model.table),[d],void 0,true),new he(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),m=await this.getSqlDataSource("write"),g=await H(p,c,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(g)?g:[g]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new z(new U(this.model.table),s,void 0,true),this.onDuplicateNode=new he(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async c=>{let{columns:m,values:g}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),f=Object.fromEntries(m.map((b,w)=>[b,g[w]]));a.push(f);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:u}=this.astParser.parse([new z(new U(this.model.table),a,void 0,true),new he(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),p=await H(l,u,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(p)?p:[p]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=v=>this.interpreterUtils.formatStringColumn("mssql",v),d=[],p=e.map(v=>`select ${a.map($=>(d.push(v[$]),`@${d.length}`)).join(", ")}`),c=a.map(u).join(", "),m=p.join(" union all "),g=r.map(v=>`target.${u(v)} = source.${u(v)}`).join(" and "),f=o.filter(v=>!r.includes(v)).map(v=>`target.${u(v)} = source.${u(v)}`).join(", "),b=a.map(u).join(", "),w=a.map(v=>`source.${u(v)}`).join(", "),q=n.returning&&n.returning.length?n.returning.map(v=>`inserted.${u(v)}`).join(", "):a.map(v=>`inserted.${u(v)}`).join(", "),R=(n.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",A=`merge into ${l} as target using (${m}) as source (${c}) on ${g} ${R} when not matched then insert (${b}) values (${w}) output ${q};`,D=await this.getSqlDataSource("write"),C=await H(A,d,D,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(C)?C:[C]}update(e,r){let o=Object.keys(e),n=Object.values(e);this.updateNode=new _e(this.fromNode,o,n,false,r);let s=r&&r.length>0;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:a,values:l}=await this.interpreterUtils.prepareColumns(o,n,"update");this.updateNode=new _e(this.fromNode,a,l,false,r);let{sql:u,bindings:d}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),p=await this.getSqlDataSource("write");return H(u,d,p,this.dbType,s?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:s?"fetch":"affectedRows"}})})}truncate(){return this.truncateNode=new at(this.fromNode),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await H(e,r,o,this.dbType,"rows");})}delete(e){this.deleteNode=new rt(this.fromNode,false,e);let r=e&&e.length>0;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:o,bindings:n}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),s=await this.getSqlDataSource("write");return H(o,n,s,this.dbType,r?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=He()}=e||{};return this.updateNode=new _e(this.fromNode,[r],[o]),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new _e(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return H(a,l,u,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return Ge(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),o=Xe(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new me("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes());return {sql:this.withQuery?`${this.withQuery} ${e}`:e,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=L(this.modelSelectedColumns),e.distinctNode=L(this.distinctNode),e.distinctOnNode=L(this.distinctOnNode),e.selectNodes=L(this.selectNodes),e.withQuery=L(this.withQuery),e.joinNodes=L(this.joinNodes),e.whereNodes=L(this.whereNodes),e.groupByNodes=L(this.groupByNodes),e.havingNodes=L(this.havingNodes),e.orderByNodes=L(this.orderByNodes),e.lockQueryNodes=L(this.lockQueryNodes),e.unionNodes=L(this.unionNodes),e.withNodes=L(this.withNodes),e.fromNode=L(this.fromNode),e.limitNode=L(this.limitNode),e.offsetNode=L(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new me("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}async manyWithPerformance(e="millis"){let[r,o]=await j(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await j(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await j(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await j(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await j(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await j(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await j(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await j(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await j(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await j(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await j(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await j(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await j(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}}};function Cp(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:Zf(i)}function Zf(i){let{parentCount:t,relationType:e,hasLimitOffset:r}=i;return r&&(e==="hasMany"||e==="manyToMany")?"batched":t===1?"join":e==="manyToMany"?typeof t=="number"&&t<=10?"join":"batched":typeof t=="number"&&t<10?"join":"batched"}var $e=class i extends Q{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this)};this.sqlModelManagerUtils=new gt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[o,n]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(o,n.columnName);}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new h(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a));if(!o.length)return [];let n=await Oe(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await Ft(r,o,n,e,{onData:async(a,l)=>{let u=this.addAdditionalColumnsToModel(l),d=await Oe([u],this.model,this.modelSelectedColumns);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),a.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new h(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}upsert(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return n.upsertMany(s,a,[l],{updateOnConflict:o.updateOnConflict??true,returning:o.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=r.length>0?Object.keys(r[0]):[];return n.upsertMany(e,s,r,{updateOnConflict:o.updateOnConflict??true,returning:o.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource;return new Pe(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,o){return this.getModelManager(o?.trx).updateRecord(e,r,o)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let o=this.model.primaryKey;if(!o)throw new h(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,o){let{column:n=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[n]:s};return this.getModelManager(o?.trx).updateRecord(e,a,{returning:o?.returning})}async firstOrInsert(e,r,o){let n=this.getModelManager(o?.trx),s=await n.findOne({where:e,ignoreHooks:["afterFetch","beforeFetch"]});if(s)return s;let a={...e,...r};return n.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,o,n,s={}){if(Array.isArray(o)||(o=[o]),!o.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new h(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=V(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=V(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=o.map((m,g)=>({[l]:r[this.model.primaryKey],[u]:m[a.model.primaryKey],...n?n(m,g):{}}));class p extends Me{static get table(){return a.throughModel}}p.databaseCaseConvention="preserve",p.modelCaseConvention="preserve",await new Pe(p,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let o=r.returning,n=super.update(e,o);return new G(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),n))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new G(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=e.returning,o=super.delete(r);return new G(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),o))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,u]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:Ut(e,r,u),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof Q)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,o){let n,s={strategy:"auto"};typeof r=="function"?(n=r,o&&(s=o)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,n?.(l),this.relationQueryBuilders.push(l),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereExists(d),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereExists(d),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereNotExists(d),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=L(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);}));}async processRelationsWithStrategy(e){let r=e.length,o=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),n=async s=>{let a=Cp({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of o)await n(s);return}await Promise.all(o.map(n));}async loadRelationViaJoin(e,r){let o=e.relation,n=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,o,n).many({ignoreHooks:["beforeFetch","afterFetch"]});this.mapJoinedResultsToModels(a,r,o,n);}buildJoinQuery(e,r,o){let n=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)n.selectNodes.push(L(s));else for(let[s]of this.model.getColumnsByDatabaseName())n.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=L(s);this.qualifyWhereNodeColumns(a,this.model.table),n.whereNodes.push(a);}for(let s of this.groupByNodes)n.groupByNodes.push(L(s));for(let s of this.orderByNodes)n.orderByNodes.push(L(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(n.limitNode=L(this.limitNode)),this.offsetNode&&(n.offsetNode=L(this.offsetNode))),r.type){case "hasOne":case "hasMany":n.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":n.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;n.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),n.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(n,r,e,o);for(let s of e.whereNodes)n.whereNodes.push(L(s));for(let s of e.orderByNodes)n.orderByNodes.push(L(s));return n}selectRelationColumnsWithAlias(e,r,o,n){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=o.selectNodes.filter(c=>typeof c.column=="string"),p=d.some(c=>c.column==="*"||c.column.endsWith(".*"));if(d.length===0||p)for(let[c,m]of u)e.selectRaw(`${a.table}.${c} as ${s}${n}${m.columnName}`);else for(let c of d){let m=c.column,g=m.includes(".")?m.split(".").pop():m,f=u.get(g)||l.get(g),b=f?.databaseName??g,w=c.alias??f?.columnName??g;e.selectRaw(`${a.table}.${b} as ${s}${n}${w}`);}}mapJoinedResultsToModels(e,r,o,n){let{columnName:s,type:a}=o,l=o.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let p=d[this.model.primaryKey];u.has(p)||u.set(p,[]);let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.get(p).push(c));}),r.forEach(d=>{let p=d[this.model.primaryKey];d[s]=u.get(p)||[];});}else {let u=new Map;e.forEach(d=>{let p=d[this.model.primaryKey];if(!u.has(p)){let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.set(p,c));}}),r.forEach(d=>{let p=d[this.model.primaryKey];d[s]=u.get(p)||null;});}}extractRelationDataFromRow(e,r,o){let n=`${r}${o}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(n)){let d=u.substring(n.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof x)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof ye)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Se)for(let o of e.nodes)this.qualifyWhereNodeColumns(o,r);}serializeRelationData(e,r){for(let o of Object.keys(e)){let n=r.get(o);n?.serialize&&e[o]!==null&&e[o]!==void 0&&(e[o]=n.serialize(e[o]));}}async loadRelationViaBatch(e,r){let o=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,o);}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let m=c[e.foreignKey];m&&n.set(String(m),c);}),r.forEach(c=>{let m=c[this.model.primaryKey];if(!m){c[e.columnName]=null;return}let g=n.get(String(m));c[e.columnName]=g||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let m=c[e.model.primaryKey];m&&s.set(String(m),c);}),r.forEach(c=>{let m=c[e.foreignKey];if(!m){c[e.columnName]=null;return}let g=s.get(String(m));c[e.columnName]=g||null;});break;case "hasMany":if(!this.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let m=c[e.foreignKey];if(!m)return;let g=String(m);a.has(g)||a.set(g,[]),a.get(g).push(c);}),r.forEach(c=>{let m=c[this.model.primaryKey];if(!m){c[e.columnName]=[];return}let g=a.get(String(m))||[];c[e.columnName]=g;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,p=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||V(d,this.model.modelCaseConvention);o.forEach(c=>{let m=c[p];if(m==null)return;let g=String(m);u.has(g)||u.set(g,[]),delete c[p],u.get(g).push(c);}),r.forEach(c=>{let m=c[this.model.primaryKey];if(!m){c[e.columnName]=[];return}let g=u.get(String(m))||[];c[e.columnName]=g;});break;default:throw new h(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=Ce.randomBytes(6).toString("hex"),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(C=>C.isRawValue?C.column:`${this.interpreterUtils.formatStringColumn(this.dbType,C.column)} ${C.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let p=e.with(u,C=>C.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,n));s&&p.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&p.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(C=>Vr(C,u,e.model.table));return p.select(...c).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new h(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let m=r;if(!o.length)return e;let g=e.limitNode?.limit,f=e.offsetNode?.offset,b=e.modelSelectedColumns.length?e.modelSelectedColumns.map(C=>C.includes(".")?C:`${r.model.table}.${C}`):[`${r.model.table}.*`];if(!g&&!f)return e.select(...b).select([`${m.throughModel}.${m.leftForeignKey}`,m.leftForeignKey]).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n);let w=Ce.randomBytes(6).toString("hex"),q=`${r.model.table}_cte_${w}`,M=e.orderByNodes.map(C=>{if(C.isRawValue)return C.column;let v=C.column.includes(".")?C.column:`${r.model.table}.${C.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,v)} ${C.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Ce.randomBytes(6).toString("hex")}_left_foreign_key`,A=e.with(q,C=>C.select(...b).select([`${m.throughModel}.${m.leftForeignKey}`,R]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${m.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,m.leftForeignKey)} ORDER BY ${M}) as rn_${w}`).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n));g&&A.whereRaw(`rn_${w} <= ${g+(f||0)}`),f&&A.whereRaw(`rn_${w} > ${f}`);let D=b.map(C=>Vr(C,q,e.model.table));return A.select(...D).select([`${q}.${R}`,m.leftForeignKey]).table(q);default:throw new h(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new h(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 h(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new h(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 h(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new h(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new h(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(m=>!m.isRawValue&&m.table===u.throughModel&&m.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let p=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${p} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(p).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new h(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e){let r={};return Object.entries(e).forEach(([o,n])=>{if(this.modelColumnsDatabaseNames.get(o)){r[o]=n;return}r[o]=n;}),r}async manyWithPerformance(e={},r="millis"){let[o,n]=await j(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await j(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await j(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await j(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 j(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await j(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await j(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await j(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await j(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await j(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await j(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}async insertWithPerformance(e,r="millis"){let[o,n]=await j(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await j(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}};var Fa=class{constructor(t,e,r){this.sqlDataSource=t,this.typeofModel=e,this.modelData=r;}merge(t){this.modelData={...this.modelData,...t};}getQueryBuilder(){return new $e(this.typeofModel,this.sqlDataSource)}async create(t){if(t<=0)return [];let e=this.getQueryBuilder();if(t===1)return await e.insert(this.modelData,{returning:["*"]});let r=Array.from({length:t});return await e.insertMany(r.map(()=>({...this.modelData})),{returning:["*"]})}},Xf=(i,t,e)=>new Fa(i,t,e);var lt=new Map,ve=new Map,fr=class{async get(t){return lt.get(t)}async set(t,e,r){let o=ve.get(t);if(o&&(clearTimeout(o),ve.delete(t)),lt.set(t,e),r){let n=setTimeout(()=>{lt.delete(t),ve.delete(t);},r);ve.set(t,n);}}async invalidate(t){let e=ve.get(t);e&&(clearTimeout(e),ve.delete(t)),lt.delete(t);}async invalidateAll(t){let e=lt.keys();for(let r of e)if(r.startsWith(t)){let o=ve.get(r);o&&(clearTimeout(o),ve.delete(r)),lt.delete(r);}}};var Rp=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw _.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new k("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 _.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 E={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},ey=()=>{if(!kr.existsSync(".env"))return E;try{kr.readFileSync(".env","utf8").split(`
|
|
191
|
-
`).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":E.DB_TYPE||(E.DB_TYPE=s);break;case "DB_HOST":E.DB_HOST||(E.DB_HOST=s);break;case "DB_PORT":E.DB_PORT||(E.DB_PORT=s);break;case "DB_USER":E.DB_USER||(E.DB_USER=s);break;case "DB_PASSWORD":E.DB_PASSWORD||(E.DB_PASSWORD=s);break;case "DB_DATABASE":E.DB_DATABASE||(E.DB_DATABASE=s);break;case "MIGRATION_PATH":E.MIGRATION_PATH||(E.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":E.REDIS_HOST||(E.REDIS_HOST=s);break;case "REDIS_PORT":E.REDIS_PORT||(E.REDIS_PORT=s);break;case "REDIS_USERNAME":E.REDIS_USERNAME||(E.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":E.REDIS_PASSWORD||(E.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":E.REDIS_DATABASE||(E.REDIS_DATABASE=s);break;case "MONGO_URL":E.MONGO_URL||(E.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":E.MSSQL_TRUST_SERVER_CERTIFICATE||(E.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return E}},I=
|
|
192
|
-
Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}let e=Lt(this.logs);e?.customLogger&&_.setCustomLogger(e.customLogger);}handleCockroachdbSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||I.DB_DATABASE||":memory:",this.logs=t?.logs||I.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||I.MONGO_URL,this.logs=t?.logs||I.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=1433);}handleOracleDBSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=1521);}};var ne=class{constructor(t){this.options=t;}static async createDriver(t){throw new h("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var Nt=class Nt extends ne{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new Nt(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new k("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new k("mongodb");return new Nt(this.mongoClient)}};Nt.mongoClient=null;var yr=Nt;var qt=class qt extends ne{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new qt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new k("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new k("mssql");return new qt(this.mssqlClient)}};qt.mssqlClient=null;var hr=qt;var Ct=class Ct extends ne{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Ct(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new k("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new k("mysql2");return new Ct(this.mysqlClient)}};Ct.mysqlClient=null;var gr=Ct;var Rt=class Rt extends ne{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new Rt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new k("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new k("oracledb");return new Rt(this.oracledbClient)}};Rt.oracledbClient=null;var br=Rt;var Mt=class Mt extends ne{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Mt(this.pgClient);let e=await import('pg').catch(()=>{throw new k("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new k("pg");return new Mt(this.pgClient)}};Mt.pgClient=null;var Tr=Mt;var _t=class _t extends ne{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new _t(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new k("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new k("sqlite3");return new _t(this.sqlite3Client)}};_t.sqlite3Client=null;var wr=_t;var pe=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await gr.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Tr.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await wr.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await yr.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await hr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await br.createDriver(),this.oracledbDriver;default:throw new h(`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}}};pe.mysqlDriver=null,pe.pgDriver=null,pe.sqliteDriver=null,pe.mssqlDriver=null,pe.oracledbDriver=null,pe.mongodbDriver=null;var Ua=Symbol("mongoProperties");function Sr(){return (i,t)=>{let e=K.getMetadata(Ua,i)||[];e.push(t),K.defineMetadata(Ua,e,i);}}function _p(i){return K.getMetadata(Ua,i.prototype)||[]}function Op(){return {$annotations:{}}}var dt=class extends Ie{static get collection(){if(!this._collection)throw new Error(`Collection name not set for ${this.name}. Use defineCollection() to create collections.`);return this._collection}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static async afterFetch(t){return t}};sl([Sr()],dt.prototype,"id");function ty(i){return typeof i!="function"||!i.prototype}function ry(i){let t={id:i._id?.toString()};for(let e of Object.keys(i))e!=="_id"&&(t[e]=i[e]);return t}async function Be(i,t,e){if(!t)return null;if(ty(i))return ry(t);let r=Op(),o=_p(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=V(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=V(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=V(n,i.modelCaseConvention);r[s]=null;}})),r}async function Nr(i,t,e){return (await Promise.all(t.map(async o=>await Be(i,o,e)))).filter(o=>o!==null)}var qr=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 Be(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await(this.model.afterFetch?.([o])??[o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new h("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 Nr(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await(this.model.afterFetch?.(o)??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 Be(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 Nr(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 Nr(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=te("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=te("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=te("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=te("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=te("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=te("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=te("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=te("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=te("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 _.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 _.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 _.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 _.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 _.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 _.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=te("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=te("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=te("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=te("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=te("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=te("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 Cr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=t,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 h("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new qr(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 Be(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 Be(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new h("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 h("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Be(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new h("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 Va=class extends ut{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=I.MONGO_URL);}async connect(){if(!this.url)throw new h("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 pe.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 h("MongoDataSource::getCurrentConnection mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return this.mongoClient}startSession(){if(!this.mongoClient)throw new h("MongoDataSource::startSession mongo database connection not established","CONNECTION_NOT_ESTABLISHED");let e=this.mongoClient.startSession();return e.startTransaction(),e}async disconnect(){this.mongoClient&&await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}query(e){if(!this.isConnected)throw new h("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");let r={_collection:e,collection:e,beforeInsert:void 0,beforeFetch:void 0,beforeUpdate:void 0,beforeDelete:void 0,afterFetch:void 0};return this.getModelManager(r,this).query()}from(e,r){if(!this.isConnected)throw new h("MongoDataSource::from","CONNECTION_NOT_ESTABLISHED");return this.getModelManager(e,this,r?.session)}getModelManager(e,r,o){return new Cr(e,r,o,this.logs)}};var Y=class Y{constructor(t){this.OK="OK";this.isConnected=false,this.ioRedisConnection=t;}static get ioredis(){return this.redisDataSourceInstance.ioRedisConnection}get ioredis(){return this.ioRedisConnection}static async connect(t){if(this.isConnected)return;let e=t?.port||+I.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new k("ioredis")});this.redisDataSourceInstance=new Y(new r.default({host:t?.host||I.REDIS_HOST,username:t?.username||I.REDIS_USERNAME,port:e,password:t?.password||I.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new h("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new k("ioredis")}),r=new e.default({host:t?.host||I.REDIS_HOST,username:t?.username||I.REDIS_USERNAME,port:t?.port||+I.REDIS_PORT||6379,password:t?.password||I.REDIS_PASSWORD,...t}),o=new Y(r);return await o.ioRedisConnection.ping(),o.isConnected=true,o}static async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.redisDataSourceInstance.ioRedisConnection.setex(t,r,e);return}await this.redisDataSourceInstance.ioRedisConnection.set(t,e);}catch{throw new h("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new h("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new h("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 h("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new h("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new h("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new h("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 h("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return Y.getValue(e)}catch{throw new h("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new h("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),Y.getValue(e)}catch{throw new h("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new h("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new h("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new h("RedisDataSource::disconnect","DISCONNECT_FAILED");_.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 h("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 h("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new h("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new h("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 h("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new h("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 h("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 h("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return Y.getValue(e)}catch{throw new h("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return Y.getValue(e)}catch{throw new h("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>Y.getValue(n)).filter(n=>n!==null)}catch{throw new h("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new h("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 h("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 h("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 h("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 h("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 h("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new h("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new h("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new h("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new h("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 h("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 h("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return Y.getValue(r)}catch{throw new h("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=Y.getValue(n);return r}catch{throw new h("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>Y.getValue(o))}catch{throw new h("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new h("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new h("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new h("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new h("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 h("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 h("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 h("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 h("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new h("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 h("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 h("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 h("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 h("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new h("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 h("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 h("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new h("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new h("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new h("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>Y.getValue(r)).filter(r=>r!==null)}catch{throw new h("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 h("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]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}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 h("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]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}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 h("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 h("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 h("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new h("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 h("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Y.getValue(n[a]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}return s}return n=await this.ioRedisConnection.zrange(t,e,r),n.map(s=>Y.getValue(s)).filter(s=>s!==null)}catch{throw new h("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Y.getValue(n[a]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}return s}return n=await this.ioRedisConnection.zrevrange(t,e,r),n.map(s=>Y.getValue(s)).filter(s=>s!==null)}catch{throw new h("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 h("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 h("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new h("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 h("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new h("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 h("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 h("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new h("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new h("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new h("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 h("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 h("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new h("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new h("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new h("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new h("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new h("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new h("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new h("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new h("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new h("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new h("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new h("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new h("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new h("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new h("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new h("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new h("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new h("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new h("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new h("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new h("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new h("RedisDataSource::type","TYPE_FAILED")}}static getValue(t){if(!t)return null;try{return JSON.parse(t)}catch{}return t==="true"||t==="false"?!!t:Number.isNaN(Number(t))?t:Number(t)}};Y.OK="OK";var Ja=Y;var Rr={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 xp=null;function Ve(i,t){return t.getModelManager(i)}function Ap(i,t,e){if(!t||typeof t!="object")return;let r=t;if(!r.filters)return;let o=e.getColumns();for(let[n,s]of Object.entries(r.filters)){let a=s.value;if(a==null||a==="")continue;let l=o.find(p=>p.columnName===n||p.databaseName===n);if(!l)continue;let u=typeof l.type=="string"?l.type:"string",d=Rr[u]||"string";if(d==="string"||d==="textarea"){i.whereLike(n,`%${a}%`);continue}if(d==="boolean"){i.where(n,a==="true"||a===true);continue}if(d==="date"||d==="datetime"){if(typeof a=="object"&&a!==null){let p=a;p.from&&i.where(n,">=",p.from),p.to&&i.where(n,"<=",p.to);continue}i.where(n,a);continue}i.where(n,a);}}function Ot(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 oy(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=xp;}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=Rr[a]||"string";return new r({path:s.columnName,type:l,isId:s.isPrimary,isSortable:true})})}property(n){let a=this._model.getColumns().find(d=>d.columnName===n||d.databaseName===n);if(!a)return null;let l=typeof a.type=="string"?a.type:"string",u=Rr[l]||"string";return new r({path:a.columnName,type:u,isId:a.isPrimary,isSortable:true})}async count(n){let a=Ve(this._model,this._db).query();return Ap(a,n,this._model),a.getCount()}async find(n,s={}){let l=Ve(this._model,this._db).query();return Ap(l,n,this._model),s.limit&&l.limit(s.limit),s.offset&&l.offset(s.offset),s.sort?.sortBy&&l.orderBy(s.sort.sortBy,s.sort.direction||"asc"),(await l.many()).map(d=>new e(Ot(d,this._model),this))}async findOne(n){if(!this._model.primaryKey)return null;let l=await Ve(this._model,this._db).findOneByPrimaryKey(n);return l?new e(Ot(l,this._model),this):null}async findMany(n){let s=this._model.primaryKey;return s?(await Ve(this._model,this._db).query().whereIn(s,n).many()).map(u=>new e(Ot(u,this._model),this)):[]}async create(n){let a=await Ve(this._model,this._db).insert(n,{returning:["*"]});return Ot(a,this._model)}async update(n,s){if(!this._model.primaryKey)throw new Error("Model has no primary key");let l=Ve(this._model,this._db);if(!await l.findOneByPrimaryKey(n))throw new Error("Record not found");let d=await l.updateRecord(n,s,{returning:["*"]});return Ot(d,this._model)}async delete(n){if(!this._model.primaryKey)throw new Error("Model has no primary key");let a=Ve(this._model,this._db);await a.findOneByPrimaryKey(n)&&await a.deleteRecord(n);}}}async function ny(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function sy(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),t=await oy(),e=await ny();i.default.registerAdapter({Database:e,Resource:t});}async function Ha(i,t){xp=i;let e=await import('adminjs').catch(()=>{throw new k("adminjs")});await sy();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,u]of Object.entries(t.pages))u.component&&(a[l]=u);Object.keys(a).length>0&&(n.pages=a);}return {admin:new e.default(n)}}async function Dp(i,t){let{admin:e}=await Ha(i,t),r;try{r=await import('@adminjs/express');}catch{throw new k("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var iy=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},ay=i=>i.openApi?.required??false,ly=i=>{let t=i.getColumns(),e={};for(let r of t)r.openApi?.excludeFromSwagger||(e[r.columnName]=iy(r));return e},uy=i=>{let t=i.getColumns(),e=[];for(let r of t)ay(r)&&e.push(r.columnName);return e||[]},za=i=>{let t=ly(i),e=uy(i);return {type:"object",properties:t,required:e.length?e:[]}},Gv=i=>i.map(t=>za(t)),Zv=i=>za(i),Ip=i=>i.map(t=>({...za(t),modelName:t.table,$id:t.table}));var Ya=(i,t)=>{let e=Ce.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var Mr=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var _r=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Or=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Ar=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var xr=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Qe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Dr=class extends S{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var Ir=class extends Qe{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=De(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??X(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}unsigned(){return this.columnNode.unsigned=true,this}zerofill(){return this.columnNode.zerofill=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 P?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??ue(this.tableName??"",N(this.columnNode.column))})),this):(this.namedConstraints.push(new J("unique",{columns:[N(this.columnNode.column)],constraintName:t?.constraintName||ue(this.tableName??"",N(this.columnNode.column))})),this)}check(t,e){let r=N(this.columnNode.column),o=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new J("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new J("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new Dr(t)),this)}collate(t){return this.columnNode.collate=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 Je=class extends Qe{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new Ir(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new P(e)}char(e,r=1){let o=new B(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new B(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new B(e,r);return this.build(o)}longtext(e){return this.text(e,"longtext")}mediumtext(e){return this.text(e,"mediumtext")}tinytext(e){return this.text(e,"tinytext")}uuid(e){let r=new B(e,"uuid");return this.build(r)}ulid(e){let r=new B(e,"ulid");return this.build(r)}integer(e,r=255){let o=new B(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new B(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new B(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new B(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new B(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new B(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new B(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new B(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new B(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new B(e,"numeric",{precision:r,scale:o});return this.build(n)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let o=new B(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new B(e,"time",{precision:r});return this.build(o)}year(e){let r=new B(e,"year");return this.build(r)}datetime(e,r){let o=new B(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}timestamp(e,r){let o=new B(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}boolean(e){let r=new B(e,"boolean");return this.build(r)}binary(e){let r=new B(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new B(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new B(e,"blob");return this.build(r)}tinyblob(e){let r=new B(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new B(e,"mediumblob");return this.build(r)}longblob(e){let r=new B(e,"longblob");return this.build(r)}json(e){let r=new B(e,"json");return this.build(r)}jsonb(e){let r=new B(e,"jsonb");return this.build(r)}enum(e,r){let o=new B(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new B(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new B(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new B(e,"geometry");return this.build(r)}point(e){let r=new B(e,"point");return this.build(r)}linestring(e){let r=new B(e,"linestring");return this.build(r)}polygon(e){let r=new B(e,"polygon");return this.build(r)}multiPoint(e){let r=new B(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Pr=class extends Qe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new P(t)}addColumn(t){let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(p=>p.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(p=>{let c=p;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),u=new Vt(a);u.inlineConstraints=l,this.nodes.push(u),o.getNodes().filter(p=>{let c=p;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(p=>{this.nodes.push(new ge(p));});}alterColumn(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(m=>m.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=N(s.column),l=o.getNodes().find(m=>m.constraintType==="null"),d=o.getNodes().find(m=>m.constraintType==="not_null")||l,p=o.getNodes().find(m=>m.constraintType==="default"),c={};d&&(c.nullable=d.constraintType==="null"),p&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?c.dropDefault=true:c.default=p.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(c.collate=s.collate),this.nodes.push(new Jt(N(a),s,c)),d&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(d.constraintType==="not_null"?this.nodes.push(new Zt(N(a))):d.constraintType==="null"&&this.nodes.push(new zt(N(a)))),p&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?this.nodes.push(new bt(N(a))):this.nodes.push(new Gt(N(a),p.defaultValue))),o.getNodes().forEach(m=>{let g=m;switch(g.constraintType){case "primary_key":this.addPrimaryKey(N(a));break;case "unique":this.unique(N(a),{constraintName:g.constraintName});break;case "foreign_key":this.foreignKey(N(a),g.references?.table??"",N(g.references?.columns?.[0]??""),{constraintName:g.constraintName,onDelete:g.onDelete,onUpdate:g.onUpdate});break}});}dropColumn(t){this.nodes.push(new Ht(t));}renameColumn(t,e){this.nodes.push(new Yt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new bt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new nt([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new h("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 h("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??X(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new h("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??ue(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=X(this.table,t,e);this.nodes.push(new Te(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new h("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 h("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 h("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new h("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new st(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",o=this.sqlType==="mssql",n=this.sqlType==="oracledb";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new We(t)):r?this.nodes.push(new We(t)):o?this.nodes.push(new We(t)):n&&this.nodes.push(new We(t)),this)}};var le=class{constructor(t){if(this.sqlType=t||I.DB_TYPE,!this.sqlType)throw new h("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new P(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!kr.existsSync(t))throw new h("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=mt.basename(t),r=mt.extname(e);if(r!==".sql"&&r!==".txt")throw new h("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=kr.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new Je(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new T({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?o.getMysqlOptions()||{}:{}},l=new Xt(t,n,o.getNamedConstraints(),r?.ifNotExists,a),u=s.parse([l]).sql,d=u.startsWith("create table")?u:`create table ${u}`;this.rawQuery(d),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new Pr(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 u=new be(t,s),d=n.parse([u]).sql;if(!d||!d.trim())return;let p=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(p),s=[];};for(let u of r)u.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(u);a();let l=r.filter(u=>u.file==="add_column").map(u=>u.column);this.generateAutoUpdateTriggers(t,l);}dropTable(t,e=false){let r=new er(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new be(t,[new Ye(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new at(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||Kt(t,e.join("_")),n=new rr(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new or(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new nt(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addUnique(t,e,r){let o=Array.isArray(e)?e:[e],n=r?.constraintName??ue(t,o.join("_")),s=new J("unique",{columns:o,constraintName:n}),a=new be(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=X(t,e,r),n=new Te(o),s=new be(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?ue(t,e.join("_")):ue(t,e),n=r?.constraintName??o,s=new Te(n),a=new be(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new st,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new J(...e),o=new be(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 Te(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addCheck(t,e,r){let o=r?.constraintName??`chk_${t}_custom`.substring(0,63),n=new J("check",{checkExpression:e,constraintName:o}),s=new be(t,[new ge(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new Te(e),o=new be(t,[r]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}createExtension(t,e=true){let r=new tr(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(o=>o.folder==="column"&&o.autoUpdate===true).map(o=>N(o.column));for(let o of r){let n=this.getAutoUpdateTriggerSql(t,o);for(let s of n)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];case "oracledb":return [`CREATE OR REPLACE TRIGGER "${r}" BEFORE UPDATE ON "${t}" FOR EACH ROW BEGIN :NEW."${e}" := CURRENT_TIMESTAMP; END;`];default:return []}}generateAstInstance(t){return new T(t,this.sqlType)}};var $r,Ep,At=class{constructor(t,e){il(this,$r);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new le(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=al(this,$r,Ep).call(this)),this.executionPromise.then(t,e)}rawStatement(t){return this.schema.rawStatement(t)}rawQuery(t){return this.schema.rawQuery(t),this}createTable(t,e,r){return this.schema.createTable(t,e,r),this}alterTable(t,e){return this.schema.alterTable(t,e),this}dropTable(t,e=false){return this.schema.dropTable(t,e),this}renameTable(t,e){return this.schema.renameTable(t,e),this}truncateTable(t){return this.schema.truncateTable(t),this}createIndex(t,e,r){return this.schema.createIndex(t,e,r),this}dropIndex(t,e){return this.schema.dropIndex(t,e),this}addPrimaryKey(t,e){return this.schema.addPrimaryKey(t,e),this}addUnique(t,e,r){return this.schema.addUnique(t,e,r),this}addConstraint(t,e,...r){return this.schema.addConstraint(t,e,...r),this}dropPrimaryKey(t){return this.schema.dropPrimaryKey(t),this}dropForeignKey(t,e,r){return this.schema.dropForeignKey(t,e,r),this}dropUnique(t,e,r){return this.schema.dropUnique(t,e,r),this}dropConstraint(t,e){return this.schema.dropConstraint(t,e),this}createExtension(t,e=true){return this.schema.createExtension(t,e),this}toQuery(){let t=this.schema.queryStatements;return t.length===1?t[0]:t}toQueries(){return [...this.schema.queryStatements]}toString(){let t=this.schema.queryStatements;return t.length===1?t[0]||"":t.join(`;
|
|
193
|
-
`)}async execute(){if(this.state!=="executed"){if(this.state==="failed")throw this.executionError;return this.then()}}isExecuted(){return this.state==="executed"}isPending(){return this.state==="pending"}hasFailed(){return this.state==="failed"}};$r=new WeakSet,Ep=async function(){try{this.state="pending";let t=this.schema.queryStatements;if(!t.length){this.state="executed";return}for(let e of t)await this.dataSource.rawQuery(e);this.state="executed";}catch(t){throw this.state="failed",this.executionError=t,t}};var Er=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 u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===n.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(u=>u.table===n.table);if(l){let u=l.getColumns().find(d=>d.databaseName===n.column);if(u){u.isPrimary&&a.push(`pk.${n.table}`);let d=l.getRelations();for(let p of d)p.columnName===u.columnName&&a.push(`fk.${n.table}.${p.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let u of l)s(u);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("."),u=t.relationsToDrop?.find(d=>d.table===a&&d.relation.name===l);u&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:u,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(u)});}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 u of l)u.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)}):u.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(u=>u.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Br=class Br{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new Er(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 u=r(l);return u?!(s.has(u)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new le(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===o.table)?.getColumns().find(u=>u.columnName===o.columns[0])?.primaryKeyConstraintName||De(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,u=>{let d=a||De(o.table,o.columns[0]);u.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}for(let o of t.checksToDrop||[]){let n=new le(this.sql.getDbType());n.dropCheck(o.table,o.name);let s=n.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}for(let o of t.checksToAdd||[]){let n=new le(this.sql.getDbType());n.addCheck(o.table,o.expression,{constraintName:o.name});let s=n.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=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,X(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;if(Array.isArray(r.type))s=e.enum(o[0],r.type);else if(typeof r.type=="string"&&Br.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...o);else if(typeof r.type=="string")s=e.custom(o[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||De(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new le(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=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(),m=c.primaryKey,f=c.getColumns().find(b=>b.columnName===m);if(f)n=f.databaseName;else {let b=c?.databaseCaseConvention||"preserve";n=V(m,b);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let m=c.getColumns(),g=m.find(f=>f.columnName===n);if(g)n=g.databaseName;else {let f=c.primaryKey||"id",b=m.find(w=>w.columnName===f);if(b)n=b.databaseName;else {let w=c?.databaseCaseConvention||"preserve";n=V(n||f,w);}}}else {let m=c.primaryKey||"id",f=c.getColumns().find(b=>b.columnName===m);if(f)n=f.databaseName;else {let b=c?.databaseCaseConvention||"preserve";n=V(m,b);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(c=>c.columnName===l);if(u)l=u.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=V(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(m=>m.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=V(t.relation.foreignKey,m);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,m=N(c),g=a.find(f=>f.columnName===m);if(g)l=g.databaseName;else {let f=s?.databaseCaseConvention||"preserve";l=V(m,f);}}let d=t.relation.onDelete?.toLowerCase(),p=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,c=>{let m=o||X(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:m,onDelete:d,onUpdate:p});}).toQueries()}formatSqlStatements(t){return t.map(e=>({...e,sqlStatements:e.sqlStatements.map(r=>format(r,{...this.sql.inputDetails.queryFormatOptions}).replace(/\n/g," ").replace(/\s+/g," "))}))}};Br.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var vr=Br;function py(i){return i.replace(/\s+/g," ").trim()}function fy(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ke(i,t){let e=py(t.toLowerCase()),r=fy(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var Qr=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql._models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(f=>f?.type!==void 0&&f?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let w of n.indexes)o.indexes.map(q=>q.name).includes(w.name)||e.data.indexesToAdd.push({table:r.table,index:w.name});let f=r.getUniques?.()||[];for(let w of f)e.data.uniquesToAdd.push({table:r.table,name:w.name||"mandatory",columns:w.columns});let b=r.getChecks?.()||[];for(let w of b)e.data.checksToAdd.push({table:r.table,name:w.name,expression:w.expression});for(let w of n.relations){if(w.type!=="belongsTo")continue;let q=N(w.constraintName);o.foreignKeys.find(R=>R.name===q)||e.data.relationsToAdd.push({table:r.table,relation:w,onDelete:w.onDelete,onUpdate:w.onUpdate});}return}for(let f of n.columns)o.columns.some(w=>w.name===f.databaseName||w.name===f.columnName)||e.data.columnsToAdd.push({table:r.table,column:f});let s=r.getColumns();for(let f of o.columns)s.some(w=>w.databaseName===f.name||w.columnName===f.name)||e.data.columnsToDrop.push({table:r.table,column:f.name});for(let f of n.indexes)o.indexes.map(b=>b.name).includes(f.name)||e.data.indexesToAdd.push({table:r.table,index:f.name});let a=r.getUniques?.()||[];for(let f of a)o.indexes.some(w=>w.name===f.name&&w.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:f.name||"mandatory",columns:f.columns});let l=o.foreignKeys.map(f=>f.name);for(let f of o.indexes)f.isUnique||l.includes(f.name)||n.indexes.map(w=>w.name).includes(f.name)||e.data.indexesToDrop.push({table:r.table,index:f.name});for(let f of o.indexes){if(!f.isUnique||f.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(w=>w.name).includes(f.name)||e.data.uniquesToDrop.push({table:r.table,name:f.name});}let u=r.getChecks?.()||[];for(let f of u)o.checkConstraints.some(w=>w.name===f.name)||e.data.checksToAdd.push({table:r.table,name:f.name,expression:f.expression});let d=new Set(u.map(f=>f.name)),p=n.columns.filter(f=>Array.isArray(f.type)),c=new Set(p.map(f=>f.databaseName||f.columnName));for(let f of o.checkConstraints)if(!d.has(f.name)){let b=[...c].find(w=>new RegExp(`[\\["\\[]?${w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i").test(f.expression));if(b){let w=p.find(M=>(M.databaseName||M.columnName)===b),q=o.columns.find(M=>M.name===b);if(w&&q?.enumValues&&Array.isArray(w.type)){let M=[...w.type].sort(),R=[...q.enumValues].sort();if(!(M.length===R.length&&M.every((D,C)=>D===R[C]))){e.data.checksToDrop.push({table:r.table,name:f.name});let D=e.sql.getDbType(),C=D==="mssql"?"[":'"',v=D==="mssql"?"]":'"',re=w.type.map($=>`'${$.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:f.name,expression:`${C}${b}${v} IN (${re})`});}}}else e.data.checksToDrop.push({table:r.table,name:f.name});}for(let f of n.columns){let b=o.columns.find(M=>M.name===f.databaseName||M.name===f.columnName);if(!b)continue;let w=!e.areColumnsEqual(b,f,o.indexes),q=e.getDefaultChange({table:r.table,dbColumns:b,modelColumn:f});(w||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:b,modelColumn:f});}for(let f of n.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;if(f.type==="manyToMany"&&f.manyToManyOptions){let q=N(f.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:N(f.manyToManyOptions.leftForeignKey),foreignKey:f.manyToManyOptions.leftForeignKey,constraintName:f.constraintName?N(f.constraintName):X(q,N(f.manyToManyOptions.leftForeignKey||xe(r.table)),r.table),onDelete:f.onDelete,onUpdate:f.onUpdate},onDelete:f.onDelete,onUpdate:f.onUpdate});continue}let b=N(f.constraintName);if(b&&o.foreignKeys.some(q=>q.name===b))continue;o.foreignKeys.find(q=>e.relationMatchesDbRelation(r,f,q))||e.data.relationsToAdd.push({table:r.table,relation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let m=new Set(n.relations.filter(f=>f.type==="belongsTo").map(f=>{let b=N(f.foreignKey)||f.columnName,q=r.getColumns().find(M=>M.columnName===b)?.databaseName||b;return N(f.constraintName)||X(r.table,q,f.model().table)}));for(let f of o.foreignKeys){if(f.name&&m.has(f.name))continue;n.relations.find(w=>w.type!=="belongsTo"&&w.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,w,f))||e.data.relationsToDrop.push({table:r.table,relation:f});}for(let f of n.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;let b=o.foreignKeys.find(w=>e.relationMatchesDbRelation(r,f,w));b&&!e.areRelationsEqual(b,f)&&e.data.relationsToModify.push({table:r.table,dbRelation:b,modelRelation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let g=r.primaryKey;if(g&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[g]}),o.primaryKey&&!g&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),g&&o.primaryKey){let f=r.getColumns().find(b=>b.columnName===g);f&&!e.arePrimaryKeysEqual(o.primaryKey,f)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:g});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getSqlStatementsByPhase(){let t=new vr(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=Ke(n,t.dataType),a=typeof e.type=="string"?Ke(n,e.type):void 0;if(a&&o&&(o=s===a),Array.isArray(e.type)&&(n==="mysql"||n==="mariadb")){let u=[...e.type].sort(),d=t.enumValues?[...t.enumValues].sort():null;d&&o&&(o=u.length===d.length&&u.every((p,c)=>p===d[c]));}e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let u=e.constraints.nullable,d=t.isNullable;o=o&&u===d;}if(n==="mysql"||n==="mariadb"){if(e.unsigned!==void 0||t.unsigned!==void 0){let u=e.unsigned??false,d=t.unsigned??false;o&&(o=u===d);}if(e.zerofill!==void 0||t.zerofill!==void 0){let u=e.zerofill??false,d=t.zerofill??false;o&&(o=u===d);}}return o}areRelationsEqual(t,e){let r=N(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",p=u.getColumns().find(g=>g.columnName===d),c=u.table,m=p?.databaseName||d;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===m;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=N(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===u;}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 f=n.model();f&&f.table&&(o=f);}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(),d=(n.type||"belongsTo")==="belongsTo"?N(n.foreignKey):n.columnName,p=l.find(f=>f.columnName===d);p&&(d=p.databaseName);let c=o.primaryKey||"id",g=o.getColumns().find(f=>f.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===g}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Ke(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Ke(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",u=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&u?false:"drop";if(s&&a){let d=String(t.dbColumns.defaultValue),p=String(t.modelColumn.constraints?.default),c=this.normalizeDefaultValue(e,r,d),m=this.normalizeDefaultValue(e,o||r,p);return c!==m?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=N(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find($=>$.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find($=>$.columnName===l),p=a.getColumns().find($=>$.columnName===u);if(!d||!p)continue;let c=N(o.manyToManyOptions.leftForeignKey)||l,m=N(o.manyToManyOptions.rightForeignKey)||u,g=await this.sql.getTableSchema(n);if(!g.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(d,c),this.clonePkAsColumn(p,m)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:m,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let f=this.clonePkAsColumn(d,c),b=this.clonePkAsColumn(p,m),w=g.columns.find($=>$.name===c),q=g.columns.find($=>$.name===m),M=w?this.areColumnsEqual(w,f,g.indexes):false,R=q?this.areColumnsEqual(q,b,g.indexes):false;for(let $ of g.foreignKeys){let Z=$.referencedTable===s.table,ee=$.referencedTable===a.table;if(!Z&&!ee)continue;let qe=Z?c:m,Ae=$.columns[0];Ae&&Ae!==qe&&(this.data.relationsToDrop.push({table:n,relation:$}),Ae!==c&&Ae!==m&&this.data.columnsToDrop.push({table:n,column:Ae}));}let A={};M||(A[f.databaseName]=f),R||(A[b.databaseName]=A[b.databaseName]||b);for(let $ of Object.keys(A))this.data.columnsToAdd.push({table:n,column:A[$]});let D=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),C=this.buildBelongsToRelation(n,o.model,m,u,void 0,o.onDelete,o.onUpdate),v=g.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===c),re=g.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===m);if(!v){let $=g.foreignKeys.find(Z=>Z.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(D);}if(!re){let $=g.foreignKeys.find(Z=>Z.referencedTable===a.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(C);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,p=N(a.constraintName)||X(o.table,d,a.model().table);s.add(p);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(f=>f.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(b=>b.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(b=>b.columnName===l)?.databaseName||l;let u=o.table,d=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let f=o.relation.model();u=f.table;let b=f.primaryKey||"id";d=f.getColumns().find(q=>q.columnName===b)?.databaseName||b;}let p=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(f=>{if(f.columns.length!==1||f.referencedColumns.length!==1)return false;let b=p.has(f.columns[0]),w=f.referencedTable===u,q=f.referencedColumns[0]===d;return b&&w&&q}),m=N(o.relation.constraintName)||X(o.table,l,u),g=e.get(o.table)||new Set;if(c||m&&g.has(m))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let f=N(o.relation.manyToManyOptions.throughModel),b=N(o.relation.manyToManyOptions.leftForeignKey),w=N(o.relation.manyToManyOptions.rightForeignKey),q=o.table===f&&o.relation.columnName===b&&o.relation.model().table===s?.table,M=o.table===f&&o.relation.columnName===w&&o.relation.model().table!==s?.table,R=await this.sql.getTableSchema(f),A=R.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===b&&C.referencedTable===(s?.table||"")),D=R.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===w&&C.referencedTable===o.relation.model().table);if(q&&A||M&&D)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(u=>u.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let p=a.find(b=>b.columnName===u.foreignKey)?.databaseName||u.foreignKey,c=u.model(),m=c.primaryKey||"id",f=c.getColumns().find(b=>b.columnName===m)?.databaseName||m;return o.relation.columns.length===1&&o.relation.columns[0]===p&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===f})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?N(n):X(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 Bp=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??He()});var yy=async i=>(await pe.getDriver(i)).client,Kr=async(i,t)=>{let e=await yy(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 u=e,d=t,p=d?.database;return new u.Database(p,d?.driverOptions?.mode??void 0,D=>{if(D)throw new h("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let m=e,g=t,{options:f,...b}=g.driverOptions??{},w=new m.ConnectionPool({server:g.host??"localhost",port:g.port,database:g.database,user:g.username,password:g.password,...b,options:{trustServerCertificate:I.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...f,abortTransactionOnError:false,enableImplicitTransactions:false}});return await w.connect(),w;case "oracledb":let q=e,M=t,R=`${M.host}/${M.database}`;return await q.createPool({user:M.username,password:M.password,connectString:R,...M.driverOptions});default:throw new h("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var xt=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Ce.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await t(e);return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),oe("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;oe("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new h("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");_.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw _.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new h("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");_.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 h("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new h("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw _.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 h("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){_.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new h("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 h("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 _.error(e),new k("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 h("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var Ga=Symbol.for("hysteria.orm.SqlDataSource"),Qp,Kp,ct=class i extends(Kp=ut,Qp=Ga,Kp){constructor(e){super(e);this[Qp]=true;this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new fr;this.migrationConfig={path:I.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:yt(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 i(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&Ga in e&&e[Ga]===true}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static async useConnection(e,r){let o=new i(e);await o.connect();try{await r(o),o.isConnected&&await o.disconnect();}catch(n){throw o.isConnected&&await o.disconnect(),n}}async connect(){if(this.isConnected)throw new h("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await Kr(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await Kr(e.sqlType,e.inputDetails),e.ownsPool=true;}));}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){let e=this;return new Proxy(this._models,{get(r,o){if(typeof o=="string"&&o in r)return e.from(r[o])}})}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 h("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new h("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,u=[];a?(l=r,u=o):(l=void 0,u=r!==void 0?[r,...o]:o);let d=Ya(JSON.stringify(u)),p=d?`${e}:${d}`:e,c=await this.cacheAdapter.get(p);if(c!==void 0)return c;let m=await n(...u);return await this.cacheAdapter.set(p,m,l),m}async invalidCache(e,...r){if(!this.cacheAdapter)throw new h("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new h("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=Ya(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new h("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await Kr(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this;if(typeof e=="string"){let n=new Q(Bp(e,r),o);return r?.alias&&n.table(e,r.alias),n}return new $e(e,o)}schema(){if(!this.isConnected)throw new h("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new At(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new xt(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new h("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){_.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new xt(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{let a=await e(s);return await s.commit({throwErrorOnInactiveTransaction:!1}),a}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected)throw new h("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new Pe(e,this.globalTransaction.sql):new Pe(e,this)}getPool(){if(!this.sqlPool)throw new h("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new h("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 h("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){oe("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{_.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){_.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),oe("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new h("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){_.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await Qr.makeDiff(this)).getSqlStatements();if(!o.length){_.info("No new changes detected between database schema and models metadata");return}if(_.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);_.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),_.info(`Synced schema with ${o.length} SQL statements`);}extractRowsFromRawResult(e){let r=this.getDbType();if(r==="mysql"||r==="mariadb"){if(Array.isArray(e)&&e.length>=1){let o=e[0];if(Array.isArray(o))return o;if(typeof o=="object"&&o!==null&&("insertId"in o||"affectedRows"in o))return []}return e}return r==="postgres"||r==="cockroachdb"?e&&typeof e=="object"&&"rows"in e?e.rows||[]:e:Array.isArray(e)?e:[]}async rawQuery(e,r=[],o){if(!this.isConnected)throw new h("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async s=>H(e,r,s,this.getDbType(),"raw")):H(e,r,this,this.getDbType(),"raw")}rawStatement(e){return new P(e)}async getTableSchema(e){let[r,o,n,s,a]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e),this.getCheckConstraintInfo(e)]),l=this.getDbType();if(l==="postgres"||l==="mssql")for(let u of r){let d=a.find(p=>{let c=p.expression;return new RegExp(`[\\["\\[]?${u.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(([^)]+)\\)`,"i").test(c)});if(d){let p=new RegExp("IN\\s*\\(([^)]+)\\)","i"),c=d.expression.match(p);c&&(u.enumValues=c[1].split(",").map(m=>m.trim().replace(/^'|'$/g,"")));}}return {columns:r,indexes:o,foreignKeys:n,primaryKey:s,checkConstraints:a}}getModelOpenApiSchema(){return Ip(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new h("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Ha(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new h("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await Dp(this,this.adminJsOptions),this.adminJsInstance)}getAdminJs(){return this.adminJsInstance}getAdminJsOptions(){return this.adminJsOptions}isAdminJsEnabled(){return !!this.adminJsOptions?.enabled}async getTableInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new xr(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(Ze(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),u=Ke(s,l);return {name:a.name,dataType:u,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||""),u=String(a.data_type||a.DATA_TYPE||a.type||"").toLowerCase(),d=Ke(s,u),p=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof p=="string"?p.toLowerCase()!=="no":typeof p=="boolean"?p:a.notnull!==void 0?a.notnull===0:true,m=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,g=a.char_length!=null?Number(a.char_length):null,f=a.numeric_precision!=null?Number(a.numeric_precision):null,b=a.numeric_scale!=null?Number(a.numeric_scale):null,w=a.timezone!=null?!!a.timezone:/with time zone/.test(String(a.column_type||a.udt_name||u||"").toLowerCase()),q=null,M=String(a.column_type||a.COLUMN_TYPE||""),R=M.match(/^enum\((.+)\)$/i);R&&(q=R[1].split(",").map(v=>v.trim().replace(/^'|'$/g,"")));let A=M.toLowerCase(),D=A.includes(" unsigned"),C=A.includes(" zerofill");return {name:l,dataType:d,isNullable:c,defaultValue:m,length:g,precision:f,scale:b,withTimezone:w,enumValues:q,unsigned:D,zerofill:C}})}async getIndexInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Or(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(Ze(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let u of s){let d=u.Key_name,p=u.Non_unique===0,c=l.get(d)||{name:d,columns:[],isUnique:p};c.columns.push(u.Column_name),l.set(d,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let u of s){let d=u.index_name,p=!!u.is_unique,c=l.get(d)||{name:d,columns:[],isUnique:p};c.columns.push(u.column_name),l.set(d,c);}return Array.from(l.values())}let a=[];for(let l of s){let u=l.name,d=!!l.unique,p=await this.rawQuery(`PRAGMA index_info(${u})`),m=this.extractRowsFromRawResult(p).map(g=>g.name);a.push({name:u,columns:m,isUnique:d});}return a}async getForeignKeyInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new _r(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Ze(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let u of n){let d=Number(u.id),p=l.get(d)||{name:void 0,columns:[],referencedTable:String(u.table),referencedColumns:[],onDelete:u.on_delete??null,onUpdate:u.on_update??null};p.columns.push(String(u.from)),p.referencedColumns.push(String(u.to)),l.set(d,p);}return Array.from(l.values())}let a=new Map;for(let l of n){let u=String(l.name||""),d=u||`${l.referenced_table}_${l.column_name}`,p=a.get(d)||{name:u||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};p.columns.push(String(l.column_name)),p.referencedColumns.push(String(l.referenced_column)),a.set(d,p);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Ar(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Ze(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async getCheckConstraintInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Mr(e)]).sql,n=[];try{let s=await this.rawQuery(o);n=this.extractRowsFromRawResult(s);}catch(s){if(Ze(this.getDbType(),s))return [];throw s}return n.map(s=>({name:String(s.name),expression:String(s.expression)}))}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
|
|
190
|
+
ORDER BY pk`,bindings:[]}}},up=new Ia;var $a=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},dp=new $a;var Pa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new T(this.model,"sqlite").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new T(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new y(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new T(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},cp=new Pa;var Ea=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=ce.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}},mp=new Ea;var va=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:[]}}},pp=new va;var Ba=class{toSql(t){let e=t,r=new T(this.model,"sqlite"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},fp=new Ba;var Ka=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new 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 u=e.values[l];return u instanceof $?`${r.formatStringColumn("sqlite",a)} = ${u.rawValue}`:(n.push(u),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},yp=new Ka;var Qa=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}},hp=new Qa;var ka=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new T(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},gp=new ka;var La=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}}},bp=new La;var Wa=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new T(this.model,"sqlite"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new T(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Tp=new Wa;var ja=class{toSql(t){let e=t,r=new T(this.model,"sqlite"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},wp=new ja;var Np={mssql:{alter_table:{add_column:Al,add_constraint:xl,add_primary_key:Dl,alter_column_type:Il,alter_table:$l,drop_column:Pl,drop_constraint:El,drop_default:vl,drop_not_null:kl,drop_primary_key:Ll,rename_column:Wl,rename_table:jl,set_default:Fl,set_not_null:Ul,set_table_options:Vl},column:{column_type:Jl},constraint:{after:Hl,constraint:zl},create_table:{create_table:Yl},delete:{delete:Gl},distinct:{distinct:Zl,distinct_on:Xl},drop_table:{drop_table:eu},extension:{create_extension:tu},from:{from:ru},group_by:{group_by:ou},having:{having:nu},index_op:{create_index:su,drop_index:iu},insert:{insert:au},join:{join:lu},limit:{limit:uu},lock:{lock:du},offset:{offset:cu},on_duplicate:{on_duplicate:mu},order_by:{order_by:pu},raw:{raw:fu},schema:{check_constraint_info:yu,foreign_key_info:hu,index_info:gu,primary_key_info:bu,table_info:Tu},select:{select:wu,select_json:Nu},truncate:{truncate:Su},union:{union:qu},update:{update:Cu},where:{where:Ru,where_group:Mu,where_json:_u,where_subquery:Ou},with:{with:Au}},mysql:{alter_table:{add_column:xu,add_constraint:Du,add_primary_key:Iu,alter_column_type:$u,alter_table:Pu,drop_column:Eu,drop_constraint:vu,drop_default:Bu,drop_not_null:Ku,drop_primary_key:Qu,rename_column:ku,rename_table:Lu,set_default:Wu,set_not_null:ju,set_table_options:Fu},column:{column_type:Uu},constraint:{after:Vu,constraint:Ju},create_table:{create_table:Hu},delete:{delete:zu},distinct:{distinct:Yu,distinct_on:Gu},drop_table:{drop_table:Zu},extension:{create_extension:Xu},from:{from:ed},group_by:{group_by:td},having:{having:rd},index_op:{create_index:od,drop_index:nd},insert:{insert:sd},join:{join:id},limit:{limit:ad},lock:{lock:ld},offset:{offset:ud},on_duplicate:{on_duplicate:dd},order_by:{order_by:cd},raw:{raw:md},schema:{check_constraint_info:pd,foreign_key_info:fd,index_info:yd,primary_key_info:hd,table_info:gd},select:{select:bd,select_json:Td},truncate:{truncate:wd},union:{union:Nd},update:{update:Sd},where:{where:qd,where_group:Cd,where_json:Rd,where_subquery:Md},with:{with:_d}},oracledb:{alter_table:{add_column:Od,add_constraint:Ad,add_primary_key:xd,alter_column_type:Dd,alter_table:Id,drop_column:$d,drop_constraint:Pd,drop_default:Ed,drop_not_null:vd,drop_primary_key:Bd,rename_column:Kd,rename_table:Qd,set_default:kd,set_not_null:Ld,set_table_options:Wd},column:{column_type:jd},constraint:{after:Fd,constraint:Ud},create_table:{create_table:Vd},delete:{delete:Jd},distinct:{distinct:Hd,distinct_on:zd},drop_table:{drop_table:Yd},extension:{create_extension:Gd},from:{from:Zd},group_by:{group_by:Xd},having:{having:ec},index_op:{create_index:tc,drop_index:rc},insert:{insert:oc},join:{join:nc},limit:{limit:sc},lock:{lock:ic},offset:{offset:ac},on_duplicate:{on_duplicate:lc},order_by:{order_by:uc},raw:{raw:dc},schema:{check_constraint_info:cc,foreign_key_info:mc,index_info:pc,primary_key_info:fc,table_info:yc},select:{select:hc,select_json:gc},truncate:{truncate:bc},union:{union:Tc},update:{update:wc},where:{where:Nc,where_group:Sc,where_json:qc,where_subquery:Cc},with:{with:Rc}},postgres:{alter_table:{add_column:Mc,add_constraint:_c,add_primary_key:Oc,alter_column_type:Ac,alter_table:xc,drop_column:Dc,drop_constraint:Ic,drop_default:$c,drop_not_null:Pc,drop_primary_key:Ec,rename_column:vc,rename_table:Bc,set_default:Kc,set_not_null:Qc,set_table_options:kc},column:{column_type:Lc},constraint:{after:Wc,constraint:jc},create_table:{create_table:Fc},delete:{delete:Uc},distinct:{distinct:Vc,distinct_on:Jc},drop_table:{drop_table:Hc},extension:{create_extension:zc},from:{from:Yc},group_by:{group_by:Gc},having:{having:Zc},index_op:{create_index:Xc,drop_index:em},insert:{insert:tm},join:{join:rm},limit:{limit:om},lock:{lock:nm},offset:{offset:sm},on_duplicate:{on_duplicate:im},order_by:{order_by:am},raw:{raw:lm},schema:{check_constraint_info:um,foreign_key_info:dm,index_info:cm,primary_key_info:mm,table_info:pm},select:{select:fm,select_json:ym},transaction:{},truncate:{truncate:hm},union:{union:gm},update:{update:bm},where:{where:Tm,where_group:wm,where_json:Nm,where_subquery:Sm},with:{with:qm}},sqlite:{alter_table:{add_column:Cm,add_constraint:Rm,alter_column_type:Mm,alter_table:_m,drop_column:Om,drop_constraint:Am,drop_default:xm,drop_not_null:Dm,drop_primary_key:Im,rename_column:$m,rename_table:Pm,set_default:Em,set_not_null:vm,set_table_options:Bm},column:{column_type:Km},constraint:{after:Qm,constraint:km},create_table:{create_table:Lm},delete:{delete:Wm},distinct:{distinct:jm,distinct_on:Fm},drop_table:{drop_table:Um},extension:{create_extension:Vm},from:{from:Jm},group_by:{group_by:Hm},having:{having:zm},index_op:{create_index:Ym,drop_index:Gm},insert:{insert:Zm},join:{join:Xm},limit:{limit:ep},lock:{lock:tp},offset:{offset:rp},on_duplicate:{on_duplicate:op},order_by:{order_by:np},raw:{raw:sp},schema:{check_constraint_info:ip,foreign_key_info:ap,index_info:lp,primary_key_info:up,table_info:dp},select:{select:cp,select_json:mp},transaction:{},truncate:{truncate:pp},union:{union:fp},update:{update:yp},where:{where:hp,where_group:gp,where_json:bp,where_subquery:Tp},with:{with:wp}}};var T=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(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"),u=l.some(R=>R.folder==="offset"),d=l.some(R=>R.folder==="order_by"),p=l.find(R=>R.folder==="limit"),c=l.find(R=>R.folder==="offset"),m=this.dbType==="mssql"&&p&&!u&&!d,g=this.dbType==="mssql"&&!m&&(p||c),f=this.dbType==="oracledb"&&(p||c),b=[],w=[],q=null;m&&p&&w.push(p.limit);for(let R=0;R<l.length;R++){let A=l[R];if(m&&A.folder==="limit"||g&&(A.folder==="limit"||A.folder==="offset")||f&&(A.folder==="limit"||A.folder==="offset"))continue;A.currParamIndex=e+w.length;let D=Np[this.mapCommonDbType(this.dbType)][A.folder][A.file];if(!D)throw new Error(`Interpreter not found for ${this.dbType} ${A.keyword}`);D.model=this.model;let C=D.toSql(A);if(!C.sql||!C.sql.trim().length)continue;let v=l[R+1],P=!v||v.keyword!==A.keyword?"":v.chainsWith;if(A.folder==="lock"||A.folder==="on_duplicate"||A.folder==="schema"){b.push(`${C.sql}${P}`),w.push(...C.bindings),q=A.keyword;continue}if(q!==A.keyword||A.canKeywordBeSeenMultipleTimes){if(r)b.push(`${C.sql}${P}`);else {let X=A.keyword;if(A.folder==="with"&&this.dbType!=="mssql"){let ee=R,Re=false;for(;ee<l.length&&l[ee].keyword===A.keyword;){let xe=l[ee];if(xe.folder==="with"&&xe.clause==="recursive"){Re=true;break}ee++;}Re&&(X=`${X} recursive`);}if(X==="select"){let ee=m?`top (@${e}) `:"";if(o){let Re=Array.isArray(o.columns)?o.columns.join(", "):"";b.push(`select ${ee}distinct on (${Re}) ${C.sql}${P}`);}else n?b.push(`select ${ee}distinct ${C.sql}${P}`):b.push(`select ${ee}${C.sql}${P}`);}else X==="from"&&a?b.push(`${X} ${C.sql}${a}${P}`):b.push(`${X} ${C.sql}${P}`);}q=A.keyword;}else b.push(`${C.sql}${P}`);w.push(...C.bindings);}if(g){d||b.push("order by (select null)");let R=c?.offset??0;w.push(R);let D=`offset @${e+w.length-1} rows`;if(p){w.push(p.limit);let C=e+w.length-1;D+=` fetch next @${C} rows only`;}b.push(D);}if(f){d||b.push("order by null");let R=c?.offset??0;w.push(R);let D=`offset :${e+w.length-1} rows`;if(p){w.push(p.limit);let C=e+w.length-1;D+=` fetch next :${C} rows only`;}b.push(D);}return {sql:b.join(" "),bindings:w}}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 zf=i=>{if(i==null||typeof i!="object"||i instanceof Date)return false;if(Array.isArray(i))return true;let t=Object.getPrototypeOf(i);return t===Object.prototype||t===null},y=class{constructor(t){this.model=t;this.modelColumnsMap=typeof t.getColumnsByName=="function"?t.getColumnsByName():new Map;let e=[],r=[];for(let o of this.modelColumnsMap.values())(o.prepare||o.autoUpdate)&&e.push(o),o.autoUpdate&&r.push(o);this.autoInsertColumns=e,this.autoUpdateColumns=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??V(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??V(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 d=0;d<t.length;d++){let p=t[d],c=e[d];p!=="*"&&(o.push(p),n.push(c));}let s=new Set(o),a=null;for(let d=0;d<o.length;d++){let p=o[d],c=n[d],m=this.modelColumnsMap.get(p);if(m){if(m.prepare){let g=r==="insert"?m.prepare(c):m.prepare(c)??c;g!==null&&typeof g?.then=="function"?(a||(a=[]),a.push({index:d,promise:g})):n[d]=g;}}else zf(c)&&(n[d]=JSON.stringify(c));}if(a){let d=await Promise.all(a.map(p=>p.promise));for(let p=0;p<a.length;p++)n[a[p].index]=d[p];}let l=this.model.primaryKey,u=r==="insert"?this.autoInsertColumns:this.autoUpdateColumns;for(let d of u){let p=d.columnName;if(s.has(p)||r==="insert"&&p===l&&!d.prepare)continue;o.push(p);let c=d.prepare?await d.prepare(void 0):void 0;n.push(c??void 0);}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new T(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var rt=class extends N{constructor(e,r=false,o){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e,this.returning=o;}};var U=class extends N{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var Y=class extends N{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var ge=class extends N{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 N{constructor(e,r=[],o=[],n=false,s){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o,this.returning=s;}};var Sp;Sp=Symbol.toStringTag;var Z=class{constructor(t,e,r,o){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=o;this[Sp]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}toSql(){return this.toSqlFn()}unWrap(){return this.unWrapFn()}};var Yf=async(i,t,e,r,o,n=false)=>{let s=Object.create(t.prototype),a=null;for(let l of Object.keys(i)){let u=i[l],d=r.get(l)?.columnName??l,p=e.has(d),c=n?true:o?o.has(d):true;if(p){if(!c)continue;if(u===null){s[d]=null;continue}let m=e.get(d);if(m?.serialize){let g=m.serialize(u);g!==null&&typeof g?.then=="function"?(a||(a=[]),a.push({key:d,promise:g})):s[d]=g;continue}s[d]=u;continue}(!n||o&&o.has(d))&&(s[d]=u);}if(a){let l=await Promise.all(a.map(u=>u.promise));for(let u=0;u<a.length;u++)s[a[u].key]=l[u];}if(o)for(let l of o)l in s||(s[l]=null);return s},Ae=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),o=t.getColumnsByDatabaseName(),n=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let m=u.match(/\s+as\s+(.+)$/i);m&&s.push(m[1].trim());continue}let p=u;if(p.includes(".")&&(p=p.split(".").pop()),p==="*")continue;let c=r.get(p)?.columnName??p;s.push(c);}let a=s.length?new Set(s):null,l=await Promise.all(i.map(u=>Yf(u,t,r,o,a,n)));return l.length===1?l[0]:l};var k=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Gf=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,Zf=/^\d{4}-\d{2}-\d{2}$/,Fa=i=>typeof i!="string"?i:Gf.test(i)?new Date(i.replace(" ","T")+"Z"):Zf.test(i)?new Date(i+"T00:00:00Z"):i,Xf=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),qp=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Xf(r):t[e]=r;}return t};var jt=class extends 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:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(u=>{r=true,this.emit("error",u);}).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);});}},Cp=(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((u,d)=>{n.run(i,t,function(p){p&&d(p),u(this.changes);});});if(r.mode==="fetch")return new Promise((u,d)=>{n.all(i,t,(p,c)=>{p&&d(p),(!c||!c.length)&&u([]),u(c);});});let s=r?.typeofModel;if(!s)return new Promise((u,d)=>{n.run(i,t,function(p){p?d(new Error(p.message)):u(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((p,c)=>{n.run(i,t,function(m){if(m)return c(m);let g=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){p([g]);return}let f=g?.[a]||this.lastID;if(!f)return c(new h("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let b=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(b,[f],(w,q)=>{if(w)return c(w);p([q]);});});});if(!Array.isArray(r.models))throw new h("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let u=r.models;if(!a)return new Promise((p,c)=>{n.run(i,t,function(m){if(m)return c(m);p(u);});});let d=[];return new Promise(async(p,c)=>{try{let m=u.map(async g=>{let f=new y(s),{columns:b,values:w}=await f.prepareColumns(Object.keys(g),Object.values(g),"insert"),q=Object.fromEntries(b.map((D,C)=>[D,w[C]])),M=new T(s,e.getDbType()),{sql:R,bindings:A}=M.parse([new Y(new U(s.table),[q])]);return new Promise((D,C)=>{n.run(R,A,function(v){if(v)return C(v);let re=g[a]||this.lastID;if(!re)return C(new h("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let P=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(P,[re],(X,ee)=>{if(X)return C(X);D(ee);});});})});d=await Promise.all(m),p(d);}catch(m){c(m);}})}return new Promise((u,d)=>{n.run(i,t,function(p){p?d(new Error(p.message)):u(this.changes);});})};var H=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||oe(i,e.logs,t,e.inputDetails.queryFormatOptions,r),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await ht(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),u=0,d=i.replace(/\?/g,()=>`$${++u}`),p=await ht(()=>l.query(d,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let c=await ht(()=>Cp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(c)?c:[c]:c;case "mssql":let m=e.getPool(),g=e.sqlConnection?e.sqlConnection.request():m.request();t.forEach((A,D)=>{g.input(`p${D}`,A);});let f=0,b=i.replace(/\?|@(\d+)/g,()=>`@p${f++}`),w=await ht(()=>g.query(b),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?w.rowsAffected[0]:o==="raw"?w:w.recordset;case "oracledb":let q=4002,M=null,R=!!e.sqlConnection;try{M=e.sqlConnection?e.sqlConnection:await e.getConnection();let A=t.map(Fa),D=0,C=i.replace(/\?/g,()=>`:${++D}`),v=await ht(()=>M.execute(C,A,{outFormat:q,autoCommit:!R}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?v.rowsAffected:o==="raw"?v:await Promise.all(v.rows?.map(async P=>{let X=await qp(P),ee={};for(let Re in X)ee[Re.toLowerCase()]=X[Re];return ee})??[])}finally{M&&!R&&await M.close();}default:throw new h("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},Ut=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 PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),p=0,c=false,m=false,g=()=>{try{a.release();}catch{}};return d.on("data",f=>{if(o.onData){p++,Promise.resolve(o.onData(l,f)).then(()=>{p--,c&&p===0&&!m&&(g(),l.end());}).catch(b=>{m=true,g(),l.destroy(b);});return}l.write(f);}),d.on("end",()=>{c=true,p===0&&!m&&(g(),l.end());}),d.on("error",f=>{m=true,g(),l.destroy(f);}),l.on("close",()=>{g();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new k("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,p=i.replace(/\?/g,()=>`$${++d}`),c=new l.default(p,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),m=a.query(c),g=0,f=false,b=false,w=q=>{try{a.release(q);}catch{}};return m.on("data",q=>{if(o.onData){g++,Promise.resolve(o.onData(u,q)).then(()=>{g--,f&&g===0&&!b&&(w(),u.end());}).catch(M=>{b=true,w(M),u.destroy(M);});return}u.write(q);}),m.on("end",()=>{f=true,g===0&&!b&&(w(),u.end());}),m.on("error",q=>{b=true,w(q),u.destroy(q);}),u}case "sqlite":{let s=e.sqlConnection??e.getPool();return new jt(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((g,f)=>{l.input(`p${f}`,g);});let u=0,d=i.replace(/\?|@(\d+)/g,()=>`@p${u++}`),p=0,c=false,m=false;return l.on("row",g=>{if(!m){if(o.onData){p++,Promise.resolve(o.onData(a,g)).then(()=>{p--,c&&p===0&&!m&&a.end();}).catch(f=>{m=true,a.destroy(f);});return}a.write(g);}}),l.on("error",g=>{m=true,a.destroy(g);}),l.on("done",()=>{c=true,p===0&&!m&&a.end();}),l.query(d),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=4002,d=0,p=i.replace(/\?/g,()=>`:${++d}`),c=t.map(Fa),m=a.queryStream(p,c,{outFormat:u}),g=0,f=false,b=false,w=async()=>{try{await a.close();}catch{}};return m.on("data",q=>{if(b)return;let M={};for(let R in q)M[R.toLowerCase()]=q[R];if(o.onData){g++,Promise.resolve(o.onData(l,M)).then(()=>{g--,f&&g===0&&!b&&(w(),l.end());}).catch(R=>{b=true,w(),l.destroy(R);});return}l.write(M);}),m.on("end",()=>{f=true,g===0&&!b&&(w(),l.end());}),m.on("error",q=>{b=true,w(),l.destroy(q);}),l}default:throw new h("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function ht(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,Ql(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}function Rp(){return {}}var $e=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Rp(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new T(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new h(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new h(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(u=>[u,t[u]])),o=!e.returning||e.returning.length===0,n=new Y(new U(this.model.table),[r],e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new Z(s,a,l,async()=>{e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:u,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),p={};u.forEach((q,M)=>{let R=d[M];p[q]=R,t[q]??(t[q]=R);});let c=!e.returning||e.returning.length===0,{sql:m,bindings:g}=this.astParser.parse([new Y(new U(this.model.table),[p],e.returning,c)]),f=await H(m,g,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(f,[t],"one",e.returning);let b=f[0];return b?(await this.model.afterFetch?.([b]),await Ae([b],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(u=>Object.fromEntries(Object.keys(u).map(d=>[d,u[d]]))),o=!e.returning||e.returning.length===0,n=new Y(new U(this.model.table),r,e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new Z(s,a,l,async()=>{if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let b=this.model.primaryKey,w=Object.keys(t[0]||{});if(b&&!w.includes(b))return this.handleOracleIdentityInsert(t,e)}let u=new Array(t.length);await Promise.all(t.map(async(b,w)=>{let{columns:q,values:M}=await this.interpreterUtils.prepareColumns(Object.keys(b),Object.values(b),"insert"),R={};q.forEach((A,D)=>{let C=M[D];R[A]=C,b[A]??(b[A]=C);}),u[w]=R;}));let d=!e.returning||e.returning.length===0,{sql:p,bindings:c}=this.astParser.parse([new Y(new U(this.model.table),u,e.returning,d)]),m=await H(p,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(m,t,"many",e.returning)||[];let g=m;return g.length?(await this.model.afterFetch?.(g),await Ae(g,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(m=>[m,c[m]]))),s=new Y(new U(this.model.table),n,void 0,true),a=o.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0;new ge(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",a);let u=()=>{let c=this.astParser.parse([s]);return {sql:c.sql,bindings:c.bindings}},d=()=>{let c=this.astParser.parse([s]);return {sql:Xe(this.sqlDataSource,c.sql),bindings:c.bindings}},p=()=>{let{sql:c,bindings:m}=d();return Ge(c,m)};return new Z(u,d,p,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async A=>{let{columns:D,values:C}=await this.interpreterUtils.prepareColumns(Object.keys(A),Object.values(A),"insert"),v=Object.fromEntries(D.map((re,P)=>[re,C[P]]));c.push(v);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let m=!o.returning||o.returning.length===0,g=!m&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0,{sql:f,bindings:b}=this.astParser.parse([new Y(new U(this.model.table),c,void 0,true),new ge(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",g)]),w=await H(f,b,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(m)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(w.length<r.length&&!(o.updateOnConflict??true)){let C=t[0],v=r.map(P=>P[C]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(C,v).many()}let A=w;return await this.model.afterFetch?.(A),await Ae(A,this.model,o.returning)||[]}let q=t[0],M=r.map(A=>A[q]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(q,M).many()})}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=D=>this.interpreterUtils.formatStringColumn("mssql",D),u=[],d=t.map(D=>`select ${s.map(v=>(u.push(D[v]),`@${u.length}`)).join(", ")}`),p=s.map(l).join(", "),c=d.join(" union all "),m=e.map(D=>`target.${l(D)} = source.${l(D)}`).join(" and "),g=r.filter(D=>!e.includes(D)).map(D=>`target.${l(D)} = source.${l(D)}`).join(", "),f=s.map(l).join(", "),b=s.map(D=>`source.${l(D)}`).join(", "),w=o.returning&&o.returning.length?o.returning.map(D=>`inserted.${l(D)}`).join(", "):s.map(D=>`inserted.${l(D)}`).join(", "),M=(o.updateOnConflict??true)&&g?`when matched then update set ${g}`:"",R=`merge into ${a} as target using (${c}) as source (${p}) on ${m} ${M} when not matched then insert (${f}) values (${b}) output ${w};`,A=await H(R,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});if(A.length===0&&!(o.updateOnConflict??true)){let D=e[0],C=n.map(re=>re[D]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(D,C).many()}return A}async updateRecord(t,e,r){let o=new Set(this.model.getColumns().map(g=>g.columnName)),n=Object.keys(e).filter(g=>o.has(g)),s=n.map(g=>e[g]),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(n,s,"update"),{primaryKey:u}=this.model;if(!u)throw new h(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let{sql:p,bindings:c}=this.astParser.parse([new Oe(new U(this.model.table),a,l),new x(u,"and",false,"=",t)]);if(await H(p,c,this.sqlDataSource,this.sqlType,"affectedRows"),!r?.returning||r.returning.length===0)return;let m=await this.findOneByPrimaryKey(t,r.returning);if(!m)throw new h(this.model.name+"::updateRecord","ROW_NOT_FOUND");return m}async deleteRecord(t){if(!this.model.primaryKey)throw new h(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new x(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:o}=this.astParser.parse([new rt(new U(this.model.table)),e]);await H(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new Pe(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await Ae([a],this.model):null}return await Ae(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((m,g)=>{let f=a[g];l[m]=f,n[m]??(n[m]=f);});let{sql:u,bindings:d}=this.astParser.parse([new Y(new U(this.model.table),[l],e.returning)]);await H(u,d,this.sqlDataSource,this.sqlType,"rows");let p=this.query().select(...e.returning||["*"]);for(let[m,g]of Object.entries(l))g!=null&&m!==o&&p.where(m,"=",g);o&&p.orderBy(o,"desc");let c=await p.one({ignoreHooks:["beforeFetch"]});if(c){let m=c;o&&m[o]&&(n[o]=m[o]),r.push(c);}else r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of n)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;o?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;o?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var gt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Cl(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 h("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Vt(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 Mp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var ot=i=>typeof i=="number"?i:parseFloat(i);var Jt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var be=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var nt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Ht=class extends N{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 Te=class extends N{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 zt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var we=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var bt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Yt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var st=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Gt=class extends N{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Zt=class extends N{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Xt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var We=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var B=class extends N{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false,this.unsigned=o.unsigned,this.zerofill=o.zerofill;}};var J=class extends N{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 er=class extends N{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var tr=class extends N{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 rr=class extends N{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 or=class extends N{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 nr=class extends N{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 Tt=class extends N{constructor(e,r=false,o=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=o;}};var je=class extends N{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var it=class extends N{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 me=class extends N{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 at=class extends N{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var Fe=class extends N{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 sr=class extends N{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var ir=class extends N{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Ee=class extends N{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 ae=class extends N{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var wt=class extends N{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 ar=class extends N{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var lr=class extends N{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Nt=class extends N{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 dr=class dr{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs,typeof t.getColumns=="function"?(this.modelColumns=t.getColumns(),this.modelColumnsMap=t.getColumnsByName?.()??new Map(this.modelColumns.map(r=>[r.columnName,r]))):(this.modelColumns=[],this.modelColumnsMap=dr.EMPTY_MAP);}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new wt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new wt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Nt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Nt(t,"asc",true)),this}limit(t){return typeof t!="number"&&_.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new ar(t),this}offset(t){return typeof t!="number"&&_.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new lr(t),this}};dr.EMPTY_MAP=new Map;var ur=dr;var Ue=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",false,"in",e)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",false,"in",e)),this):(this.whereNodes.push(new x("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",true,"in",e)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",true,"in",e)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new x(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new x(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new x(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new x(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new qe(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new qe(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new x(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new x(t,"or",true,"=",e??[],true)),this}};var cr=class extends ur{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ae(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ae(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ae(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ae(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ae(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ae(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new h("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ae(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var mr=class extends cr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=V(s,this.model.databaseCaseConvention);this.selectNodes.push(new me(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=V(o,this.model.databaseCaseConvention);this.selectNodes.push(new me(n));}),this}selectRaw(e){return this.selectNodes.push(new me(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":V(r,this.model.databaseCaseConvention);return this.selectNodes.push(new me(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new U(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}table(e){return this.fromNode=new U(e),this}distinct(){return this.distinctNode=new sr,this}distinctOn(...e){return this.distinctOnNode=new ir(e),this}selectJson(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Ee(e,"",r,"raw",true)),this}};var pr=class extends mr{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof K&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof K||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 K&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof K||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof K)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 K&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof K||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof K)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"and",false,n,new $(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"or",false,n,new $(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof K&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof K||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof K)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 K&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof K||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof K)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 K&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof K||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof K)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 x(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",false,"in",r)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",false,"in",r)),this):(this.whereNodes.push(new x("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 x(e,"and",true,"in",r)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",true,"in",r)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new x(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new x(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new x(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new x(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 x(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 x(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof K?e:new K(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new he("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof K?e:new K(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new he("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof K?e:new K(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new he("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof K?e:new K(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new he("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new x(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new x(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 Fe(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 Fe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Fe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Fe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof K)return e;let r=new K(this.model,this.sqlDataSource),o=e(r);return o!=null&&"extractQueryNodes"in o?o:r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new he(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new he(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new K(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new qe(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new K(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new qe(r.whereNodes,"or");return this.whereNodes.push(o),this}};var fr=class extends pr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new ie(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new ie(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new ie(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new ie(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new ie(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new ie(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new ie(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new ie(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new ie(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new ie(t,"or",false,"raw",e)),this}};var K=class i extends fr{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new T(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new y(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource),s=r(n),a=s!=null&&"extractQueryNodes"in s?s:n;return this.selectNodes.push(new me(a.extractQueryNodes(),o)),this}return this.selectNodes.push(new me(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>H(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new h("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await Ut(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let[s,a]=await this.executePaginateQueries(()=>this.many(),()=>n.getCount()),l=s[s.length-1],u=l?l[r.discriminator]:null;return [{paginationMetadata:Mp(e,a),data:s},{key:r.discriminator,value:u}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new Tt("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Tt("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new je(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new je(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?ot(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&_.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:Vt(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new h("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource),n=e(o),a=(n!=null&&"extractQueryNodes"in n?n:o).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new it("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new it("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new h("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new it("materialized",e,s.extractQueryNodes())),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new Y(this.fromNode,[o],r,n),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((m,g)=>[m,a[g]]));this.insertNode=new Y(this.fromNode,[l],r,n);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),p=await this.getSqlDataSource("write"),c=await H(u,d,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new Y(this.fromNode,o,r,n),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async p=>{let{columns:c,values:m}=await this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert");return Object.fromEntries(c.map((g,f)=>[g,m[f]]))}));this.insertNode=new Y(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await H(a,l,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return d})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new Y(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new ge(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(l.map((f,b)=>[f,u[b]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:p,bindings:c}=this.astParser.parse([new Y(new U(this.model.table),[d],void 0,true),new ge(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),m=await this.getSqlDataSource("write"),g=await H(p,c,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(g)?g:[g]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new Y(new U(this.model.table),s,void 0,true),this.onDuplicateNode=new ge(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async c=>{let{columns:m,values:g}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),f=Object.fromEntries(m.map((b,w)=>[b,g[w]]));a.push(f);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:u}=this.astParser.parse([new Y(new U(this.model.table),a,void 0,true),new ge(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),p=await H(l,u,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(p)?p:[p]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=v=>this.interpreterUtils.formatStringColumn("mssql",v),d=[],p=e.map(v=>`select ${a.map(P=>(d.push(v[P]),`@${d.length}`)).join(", ")}`),c=a.map(u).join(", "),m=p.join(" union all "),g=r.map(v=>`target.${u(v)} = source.${u(v)}`).join(" and "),f=o.filter(v=>!r.includes(v)).map(v=>`target.${u(v)} = source.${u(v)}`).join(", "),b=a.map(u).join(", "),w=a.map(v=>`source.${u(v)}`).join(", "),q=n.returning&&n.returning.length?n.returning.map(v=>`inserted.${u(v)}`).join(", "):a.map(v=>`inserted.${u(v)}`).join(", "),R=(n.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",A=`merge into ${l} as target using (${m}) as source (${c}) on ${g} ${R} when not matched then insert (${b}) values (${w}) output ${q};`,D=await this.getSqlDataSource("write"),C=await H(A,d,D,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(C)?C:[C]}update(e,r){let o=Object.keys(e),n=Object.values(e);this.updateNode=new Oe(this.fromNode,o,n,false,r);let s=r&&r.length>0;return new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:a,values:l}=await this.interpreterUtils.prepareColumns(o,n,"update");this.updateNode=new Oe(this.fromNode,a,l,false,r);let{sql:u,bindings:d}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),p=await this.getSqlDataSource("write");return H(u,d,p,this.dbType,s?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:s?"fetch":"affectedRows"}})})}truncate(){return this.truncateNode=new at(this.fromNode),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await H(e,r,o,this.dbType,"rows");})}delete(e){this.deleteNode=new rt(this.fromNode,false,e);let r=e&&e.length>0;return new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:o,bindings:n}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),s=await this.getSqlDataSource("write");return H(o,n,s,this.dbType,r?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=He()}=e||{};return this.updateNode=new Oe(this.fromNode,[r],[o]),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{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]),u=await this.getSqlDataSource("write");return H(a,l,u,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return Ge(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),o=Xe(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new me("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes());return {sql:this.withQuery?`${this.withQuery} ${e}`:e,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=L(this.modelSelectedColumns),e.distinctNode=L(this.distinctNode),e.distinctOnNode=L(this.distinctOnNode),e.selectNodes=L(this.selectNodes),e.withQuery=L(this.withQuery),e.joinNodes=L(this.joinNodes),e.whereNodes=L(this.whereNodes),e.groupByNodes=L(this.groupByNodes),e.havingNodes=L(this.havingNodes),e.orderByNodes=L(this.orderByNodes),e.lockQueryNodes=L(this.lockQueryNodes),e.unionNodes=L(this.unionNodes),e.withNodes=L(this.withNodes),e.fromNode=L(this.fromNode),e.limitNode=L(this.limitNode),e.offsetNode=L(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new me("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}async manyWithPerformance(e="millis"){let[r,o]=await j(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await j(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await j(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await j(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await j(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await j(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await j(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await j(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await j(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await j(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await j(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await j(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await j(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}}};function _p(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:ty(i)}function ty(i){let{parentCount:t,relationType:e,hasLimitOffset:r}=i;return r&&(e==="hasMany"||e==="manyToMany")?"batched":t===1?"join":e==="manyToMany"?typeof t=="number"&&t<=10?"join":"batched":typeof t=="number"&&t<10?"join":"batched"}var Pe=class i extends K{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this)};this.sqlModelManagerUtils=new gt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[o,n]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(o,n.columnName);}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new h(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a));if(!o.length)return [];let n=await Ae(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await Ut(r,o,n,e,{onData:async(a,l)=>{let u=this.addAdditionalColumnsToModel(l),d=await Ae([u],this.model,this.modelSelectedColumns);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),a.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new h(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}upsert(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return n.upsertMany(s,a,[l],{updateOnConflict:o.updateOnConflict??true,returning:o.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=r.length>0?Object.keys(r[0]):[];return n.upsertMany(e,s,r,{updateOnConflict:o.updateOnConflict??true,returning:o.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource;return new $e(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,o){return this.getModelManager(o?.trx).updateRecord(e,r,o)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let o=this.model.primaryKey;if(!o)throw new h(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,o){let{column:n=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[n]:s};return this.getModelManager(o?.trx).updateRecord(e,a,{returning:o?.returning})}async firstOrInsert(e,r,o){let n=this.getModelManager(o?.trx),s=await n.findOne({where:e,ignoreHooks:["afterFetch","beforeFetch"]});if(s)return s;let a={...e,...r};return n.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,o,n,s={}){if(Array.isArray(o)||(o=[o]),!o.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new h(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=V(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=V(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=o.map((m,g)=>({[l]:r[this.model.primaryKey],[u]:m[a.model.primaryKey],...n?n(m,g):{}}));class p extends _e{static get table(){return a.throughModel}}p.databaseCaseConvention="preserve",p.modelCaseConvention="preserve",await new $e(p,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let o=r.returning,n=super.update(e,o);return new Z(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),n))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new Z(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=e.returning,o=super.delete(r);return new Z(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),o))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,u]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:Vt(e,r,u),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof K)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,o){let n,s={strategy:"auto"};typeof r=="function"?(n=r,o&&(s=o)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,n?.(l),this.relationQueryBuilders.push(l),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereExists(d),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereExists(d),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereNotExists(d),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),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=L(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);}));}async processRelationsWithStrategy(e){let r=e.length,o=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),n=async s=>{let a=_p({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of o)await n(s);return}await Promise.all(o.map(n));}async loadRelationViaJoin(e,r){let o=e.relation,n=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,o,n).many({ignoreHooks:["beforeFetch","afterFetch"]});this.mapJoinedResultsToModels(a,r,o,n);}buildJoinQuery(e,r,o){let n=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)n.selectNodes.push(L(s));else for(let[s]of this.model.getColumnsByDatabaseName())n.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=L(s);this.qualifyWhereNodeColumns(a,this.model.table),n.whereNodes.push(a);}for(let s of this.groupByNodes)n.groupByNodes.push(L(s));for(let s of this.orderByNodes)n.orderByNodes.push(L(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(n.limitNode=L(this.limitNode)),this.offsetNode&&(n.offsetNode=L(this.offsetNode))),r.type){case "hasOne":case "hasMany":n.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":n.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;n.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),n.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(n,r,e,o);for(let s of e.whereNodes)n.whereNodes.push(L(s));for(let s of e.orderByNodes)n.orderByNodes.push(L(s));return n}selectRelationColumnsWithAlias(e,r,o,n){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=o.selectNodes.filter(c=>typeof c.column=="string"),p=d.some(c=>c.column==="*"||c.column.endsWith(".*"));if(d.length===0||p)for(let[c,m]of u)e.selectRaw(`${a.table}.${c} as ${s}${n}${m.columnName}`);else for(let c of d){let m=c.column,g=m.includes(".")?m.split(".").pop():m,f=u.get(g)||l.get(g),b=f?.databaseName??g,w=c.alias??f?.columnName??g;e.selectRaw(`${a.table}.${b} as ${s}${n}${w}`);}}mapJoinedResultsToModels(e,r,o,n){let{columnName:s,type:a}=o,l=o.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let p=d[this.model.primaryKey];u.has(p)||u.set(p,[]);let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.get(p).push(c));}),r.forEach(d=>{let p=d[this.model.primaryKey];d[s]=u.get(p)||[];});}else {let u=new Map;e.forEach(d=>{let p=d[this.model.primaryKey];if(!u.has(p)){let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.set(p,c));}}),r.forEach(d=>{let p=d[this.model.primaryKey];d[s]=u.get(p)||null;});}}extractRelationDataFromRow(e,r,o){let n=`${r}${o}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(n)){let d=u.substring(n.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof x)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof he)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof qe)for(let o of e.nodes)this.qualifyWhereNodeColumns(o,r);}serializeRelationData(e,r){for(let o of Object.keys(e)){let n=r.get(o);n?.serialize&&e[o]!==null&&e[o]!==void 0&&(e[o]=n.serialize(e[o]));}}async loadRelationViaBatch(e,r){let o=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,o);}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let m=c[e.foreignKey];m&&n.set(String(m),c);}),r.forEach(c=>{let m=c[this.model.primaryKey];if(!m){c[e.columnName]=null;return}let g=n.get(String(m));c[e.columnName]=g||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let m=c[e.model.primaryKey];m&&s.set(String(m),c);}),r.forEach(c=>{let m=c[e.foreignKey];if(!m){c[e.columnName]=null;return}let g=s.get(String(m));c[e.columnName]=g||null;});break;case "hasMany":if(!this.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let m=c[e.foreignKey];if(!m)return;let g=String(m);a.has(g)||a.set(g,[]),a.get(g).push(c);}),r.forEach(c=>{let m=c[this.model.primaryKey];if(!m){c[e.columnName]=[];return}let g=a.get(String(m))||[];c[e.columnName]=g;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new h(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,p=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||V(d,this.model.modelCaseConvention);o.forEach(c=>{let m=c[p];if(m==null)return;let g=String(m);u.has(g)||u.set(g,[]),delete c[p],u.get(g).push(c);}),r.forEach(c=>{let m=c[this.model.primaryKey];if(!m){c[e.columnName]=[];return}let g=u.get(String(m))||[];c[e.columnName]=g;});break;default:throw new h(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.randomBytes(6).toString("hex"),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(C=>C.isRawValue?C.column:`${this.interpreterUtils.formatStringColumn(this.dbType,C.column)} ${C.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let p=e.with(u,C=>C.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,n));s&&p.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&p.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(C=>Hr(C,u,e.model.table));return p.select(...c).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new h(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let m=r;if(!o.length)return e;let g=e.limitNode?.limit,f=e.offsetNode?.offset,b=e.modelSelectedColumns.length?e.modelSelectedColumns.map(C=>C.includes(".")?C:`${r.model.table}.${C}`):[`${r.model.table}.*`];if(!g&&!f)return e.select(...b).select([`${m.throughModel}.${m.leftForeignKey}`,m.leftForeignKey]).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n);let w=Me.randomBytes(6).toString("hex"),q=`${r.model.table}_cte_${w}`,M=e.orderByNodes.map(C=>{if(C.isRawValue)return C.column;let v=C.column.includes(".")?C.column:`${r.model.table}.${C.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,v)} ${C.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Me.randomBytes(6).toString("hex")}_left_foreign_key`,A=e.with(q,C=>C.select(...b).select([`${m.throughModel}.${m.leftForeignKey}`,R]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${m.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,m.leftForeignKey)} ORDER BY ${M}) as rn_${w}`).leftJoin(m.throughModel,`${m.relatedModel}.${m.model.primaryKey}`,`${m.throughModel}.${m.rightForeignKey}`).whereIn(`${m.throughModel}.${m.leftForeignKey}`,n));g&&A.whereRaw(`rn_${w} <= ${g+(f||0)}`),f&&A.whereRaw(`rn_${w} > ${f}`);let D=b.map(C=>Hr(C,q,e.model.table));return A.select(...D).select([`${q}.${R}`,m.leftForeignKey]).table(q);default:throw new h(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new h(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 h(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new h(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 h(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new h(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new h(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(m=>!m.isRawValue&&m.table===u.throughModel&&m.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let p=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${p} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(p).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new h(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e){let r={};return Object.entries(e).forEach(([o,n])=>{if(this.modelColumnsDatabaseNames.get(o)){r[o]=n;return}r[o]=n;}),r}async manyWithPerformance(e={},r="millis"){let[o,n]=await j(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await j(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await j(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await j(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 j(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await j(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await j(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await j(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await j(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await j(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await j(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}async insertWithPerformance(e,r="millis"){let[o,n]=await j(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await j(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}};var Va=class{constructor(t,e,r){this.sqlDataSource=t,this.typeofModel=e,this.modelData=r;}merge(t){this.modelData={...this.modelData,...t};}getQueryBuilder(){return new Pe(this.typeofModel,this.sqlDataSource)}async create(t){if(t<=0)return [];let e=this.getQueryBuilder();if(t===1)return await e.insert(this.modelData,{returning:["*"]});let r=Array.from({length:t});return await e.insertMany(r.map(()=>({...this.modelData})),{returning:["*"]})}},ry=(i,t,e)=>new Va(i,t,e);var lt=new Map,ve=new Map,yr=class{async get(t){return lt.get(t)}async set(t,e,r){let o=ve.get(t);if(o&&(clearTimeout(o),ve.delete(t)),lt.set(t,e),r){let n=setTimeout(()=>{lt.delete(t),ve.delete(t);},r);ve.set(t,n);}}async invalidate(t){let e=ve.get(t);e&&(clearTimeout(e),ve.delete(t)),lt.delete(t);}async invalidateAll(t){let e=lt.keys();for(let r of e)if(r.startsWith(t)){let o=ve.get(r);o&&(clearTimeout(o),ve.delete(r)),lt.delete(r);}}};var Op=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw _.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new k("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 _.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 E={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},oy=()=>{if(!Wr.existsSync(".env"))return E;try{Wr.readFileSync(".env","utf8").split(`
|
|
191
|
+
`).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":E.DB_TYPE||(E.DB_TYPE=s);break;case "DB_HOST":E.DB_HOST||(E.DB_HOST=s);break;case "DB_PORT":E.DB_PORT||(E.DB_PORT=s);break;case "DB_USER":E.DB_USER||(E.DB_USER=s);break;case "DB_PASSWORD":E.DB_PASSWORD||(E.DB_PASSWORD=s);break;case "DB_DATABASE":E.DB_DATABASE||(E.DB_DATABASE=s);break;case "MIGRATION_PATH":E.MIGRATION_PATH||(E.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":E.REDIS_HOST||(E.REDIS_HOST=s);break;case "REDIS_PORT":E.REDIS_PORT||(E.REDIS_PORT=s);break;case "REDIS_USERNAME":E.REDIS_USERNAME||(E.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":E.REDIS_PASSWORD||(E.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":E.REDIS_DATABASE||(E.REDIS_DATABASE=s);break;case "MONGO_URL":E.MONGO_URL||(E.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":E.MSSQL_TRUST_SERVER_CERTIFICATE||(E.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return E}},I=oy();var ut=class{constructor(t){switch(this.type=t?.type||I.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 h(`Invalid database type: ${this.type}, please provide a valid database type in your input or in the .env file with the key DB_TYPE
|
|
192
|
+
Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}let e=Wt(this.logs);e?.customLogger&&_.setCustomLogger(e.customLogger);}handleCockroachdbSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||I.DB_DATABASE||":memory:",this.logs=t?.logs||I.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||I.MONGO_URL,this.logs=t?.logs||I.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=1433);}handleOracleDBSource(t){this.host=t?.host||I.DB_HOST,this.port=+t?.port||+I.DB_PORT,this.username=t?.username||I.DB_USER,this.password=t?.password||I.DB_PASSWORD,this.database=t?.database||I.DB_DATABASE,this.logs=t?.logs||I.DB_LOGS||false,this.port||(this.port=1521);}};var ne=class{constructor(t){this.options=t;}static async createDriver(t){throw new h("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var St=class St extends ne{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new St(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new k("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new k("mongodb");return new St(this.mongoClient)}};St.mongoClient=null;var hr=St;var qt=class qt extends ne{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new qt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new k("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new k("mssql");return new qt(this.mssqlClient)}};qt.mssqlClient=null;var gr=qt;var Ct=class Ct extends ne{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Ct(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new k("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new k("mysql2");return new Ct(this.mysqlClient)}};Ct.mysqlClient=null;var br=Ct;var Rt=class Rt extends ne{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new Rt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new k("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new k("oracledb");return new Rt(this.oracledbClient)}};Rt.oracledbClient=null;var Tr=Rt;var Mt=class Mt extends ne{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Mt(this.pgClient);let e=await import('pg').catch(()=>{throw new k("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new k("pg");return new Mt(this.pgClient)}};Mt.pgClient=null;var wr=Mt;var _t=class _t extends ne{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new _t(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new k("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new k("sqlite3");return new _t(this.sqlite3Client)}};_t.sqlite3Client=null;var Nr=_t;var pe=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await br.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await wr.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Nr.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await hr.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await gr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await Tr.createDriver(),this.oracledbDriver;default:throw new h(`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}}};pe.mysqlDriver=null,pe.pgDriver=null,pe.sqliteDriver=null,pe.mssqlDriver=null,pe.oracledbDriver=null,pe.mongodbDriver=null;var Ja=Symbol("mongoProperties");function Sr(){return (i,t)=>{let e=Q.getMetadata(Ja,i)||[];e.push(t),Q.defineMetadata(Ja,e,i);}}function xp(i){return Q.getMetadata(Ja,i.prototype)||[]}function Dp(){return {$annotations:{}}}var dt=class extends Ie{static get collection(){if(!this._collection)throw new Error(`Collection name not set for ${this.name}. Use defineCollection() to create collections.`);return this._collection}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static async afterFetch(t){return t}};ll([Sr()],dt.prototype,"id");function ny(i){return typeof i!="function"||!i.prototype}function sy(i){let t={id:i._id?.toString()};for(let e of Object.keys(i))e!=="_id"&&(t[e]=i[e]);return t}async function Be(i,t,e){if(!t)return null;if(ny(i))return sy(t);let r=Dp(),o=xp(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=V(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=V(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=V(n,i.modelCaseConvention);r[s]=null;}})),r}async function qr(i,t,e){return (await Promise.all(t.map(async o=>await Be(i,o,e)))).filter(o=>o!==null)}var Cr=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 Be(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await(this.model.afterFetch?.([o])??[o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new h("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 qr(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await(this.model.afterFetch?.(o)??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 Be(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 qr(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 qr(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=te("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=te("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=te("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=te("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=te("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=te("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=te("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=te("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=te("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 _.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 _.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 _.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 _.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 _.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 _.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=te("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=te("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=te("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=te("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=te("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=te("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 Rr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=t,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 h("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new Cr(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 Be(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 Be(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new h("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 h("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Be(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new h("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 Ha=class extends ut{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=I.MONGO_URL);}async connect(){if(!this.url)throw new h("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 pe.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 h("MongoDataSource::getCurrentConnection mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return this.mongoClient}startSession(){if(!this.mongoClient)throw new h("MongoDataSource::startSession mongo database connection not established","CONNECTION_NOT_ESTABLISHED");let e=this.mongoClient.startSession();return e.startTransaction(),e}async disconnect(){this.mongoClient&&await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}query(e){if(!this.isConnected)throw new h("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");let r={_collection:e,collection:e,beforeInsert:void 0,beforeFetch:void 0,beforeUpdate:void 0,beforeDelete:void 0,afterFetch:void 0};return this.getModelManager(r,this).query()}from(e,r){if(!this.isConnected)throw new h("MongoDataSource::from","CONNECTION_NOT_ESTABLISHED");return this.getModelManager(e,this,r?.session)}getModelManager(e,r,o){return new Rr(e,r,o,this.logs)}};var G=class G{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||+I.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new k("ioredis")});this.redisDataSourceInstance=new G(new r.default({host:t?.host||I.REDIS_HOST,username:t?.username||I.REDIS_USERNAME,port:e,password:t?.password||I.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new h("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new k("ioredis")}),r=new e.default({host:t?.host||I.REDIS_HOST,username:t?.username||I.REDIS_USERNAME,port:t?.port||+I.REDIS_PORT||6379,password:t?.password||I.REDIS_PASSWORD,...t}),o=new G(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 h("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new h("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new h("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 h("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new h("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new h("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new h("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 h("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return G.getValue(e)}catch{throw new h("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new h("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),G.getValue(e)}catch{throw new h("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new h("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new h("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new h("RedisDataSource::disconnect","DISCONNECT_FAILED");_.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 h("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 h("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new h("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new h("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 h("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new h("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 h("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 h("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return G.getValue(e)}catch{throw new h("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return G.getValue(e)}catch{throw new h("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>G.getValue(n)).filter(n=>n!==null)}catch{throw new h("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new h("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 h("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 h("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 h("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 h("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 h("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new h("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new h("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new h("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new h("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 h("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 h("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return G.getValue(r)}catch{throw new h("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]=G.getValue(n);return r}catch{throw new h("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>G.getValue(o))}catch{throw new h("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new h("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new h("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new h("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new h("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 h("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 h("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 h("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 h("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new h("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 h("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 h("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 h("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 h("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>G.getValue(r)).filter(r=>r!==null)}catch{throw new h("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 h("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 h("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new h("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>G.getValue(r)).filter(r=>r!==null)}catch{throw new h("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>G.getValue(r)).filter(r=>r!==null)}catch{throw new h("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>G.getValue(r)).filter(r=>r!==null)}catch{throw new h("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 h("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]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}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 h("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]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}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 h("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 h("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 h("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new h("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 h("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=G.getValue(n[a]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}return s}return n=await this.ioRedisConnection.zrange(t,e,r),n.map(s=>G.getValue(s)).filter(s=>s!==null)}catch{throw new h("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=G.getValue(n[a]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}return s}return n=await this.ioRedisConnection.zrevrange(t,e,r),n.map(s=>G.getValue(s)).filter(s=>s!==null)}catch{throw new h("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 h("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 h("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new h("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 h("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new h("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 h("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 h("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new h("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new h("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new h("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 h("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 h("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new h("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new h("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new h("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new h("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new h("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new h("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new h("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new h("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new h("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new h("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new h("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new h("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new h("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new h("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new h("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new h("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new h("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new h("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new h("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new h("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new h("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)}};G.OK="OK";var za=G;var Mr={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 $p=null;function Ve(i,t){return t.getModelManager(i)}function Ip(i,t,e){if(!t||typeof t!="object")return;let r=t;if(!r.filters)return;let o=e.getColumns();for(let[n,s]of Object.entries(r.filters)){let a=s.value;if(a==null||a==="")continue;let l=o.find(p=>p.columnName===n||p.databaseName===n);if(!l)continue;let u=typeof l.type=="string"?l.type:"string",d=Mr[u]||"string";if(d==="string"||d==="textarea"){i.whereLike(n,`%${a}%`);continue}if(d==="boolean"){i.where(n,a==="true"||a===true);continue}if(d==="date"||d==="datetime"){if(typeof a=="object"&&a!==null){let p=a;p.from&&i.where(n,">=",p.from),p.to&&i.where(n,"<=",p.to);continue}i.where(n,a);continue}i.where(n,a);}}function Ot(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 iy(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=$p;}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=Mr[a]||"string";return new r({path:s.columnName,type:l,isId:s.isPrimary,isSortable:true})})}property(n){let a=this._model.getColumns().find(d=>d.columnName===n||d.databaseName===n);if(!a)return null;let l=typeof a.type=="string"?a.type:"string",u=Mr[l]||"string";return new r({path:a.columnName,type:u,isId:a.isPrimary,isSortable:true})}async count(n){let a=Ve(this._model,this._db).query();return Ip(a,n,this._model),a.getCount()}async find(n,s={}){let l=Ve(this._model,this._db).query();return Ip(l,n,this._model),s.limit&&l.limit(s.limit),s.offset&&l.offset(s.offset),s.sort?.sortBy&&l.orderBy(s.sort.sortBy,s.sort.direction||"asc"),(await l.many()).map(d=>new e(Ot(d,this._model),this))}async findOne(n){if(!this._model.primaryKey)return null;let l=await Ve(this._model,this._db).findOneByPrimaryKey(n);return l?new e(Ot(l,this._model),this):null}async findMany(n){let s=this._model.primaryKey;return s?(await Ve(this._model,this._db).query().whereIn(s,n).many()).map(u=>new e(Ot(u,this._model),this)):[]}async create(n){let a=await Ve(this._model,this._db).insert(n,{returning:["*"]});return Ot(a,this._model)}async update(n,s){if(!this._model.primaryKey)throw new Error("Model has no primary key");let l=Ve(this._model,this._db);if(!await l.findOneByPrimaryKey(n))throw new Error("Record not found");let d=await l.updateRecord(n,s,{returning:["*"]});return Ot(d,this._model)}async delete(n){if(!this._model.primaryKey)throw new Error("Model has no primary key");let a=Ve(this._model,this._db);await a.findOneByPrimaryKey(n)&&await a.deleteRecord(n);}}}async function ay(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function ly(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),t=await iy(),e=await ay();i.default.registerAdapter({Database:e,Resource:t});}async function Ya(i,t){$p=i;let e=await import('adminjs').catch(()=>{throw new k("adminjs")});await ly();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,u]of Object.entries(t.pages))u.component&&(a[l]=u);Object.keys(a).length>0&&(n.pages=a);}return {admin:new e.default(n)}}async function Pp(i,t){let{admin:e}=await Ya(i,t),r;try{r=await import('@adminjs/express');}catch{throw new k("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var uy=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},dy=i=>i.openApi?.required??false,cy=i=>{let t=i.getColumns(),e={};for(let r of t)r.openApi?.excludeFromSwagger||(e[r.columnName]=uy(r));return e},my=i=>{let t=i.getColumns(),e=[];for(let r of t)dy(r)&&e.push(r.columnName);return e||[]},Ga=i=>{let t=cy(i),e=my(i);return {type:"object",properties:t,required:e.length?e:[]}},Xv=i=>i.map(t=>Ga(t)),eB=i=>Ga(i),Ep=i=>i.map(t=>({...Ga(t),modelName:t.table,$id:t.table}));var Za=(i,t)=>{let e=Me.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var _r=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var Or=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Ar=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var xr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var Dr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Ke=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Ir=class extends N{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var $r=class extends Ke{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=ye(this.tableName,S(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new J("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new J("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??z(this.tableName??"",S(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new J("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new J("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}unsigned(){return this.columnNode.unsigned=true,this}zerofill(){return this.columnNode.zerofill=true,this}notNullable(){return this.nodes.push(new J("not_null",{columns:[S(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new J("null",{columns:[S(this.columnNode.column)]})),this}default(t){let e;return t instanceof $?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new J("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new J("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??ue(this.tableName??"",S(this.columnNode.column))})),this):(this.namedConstraints.push(new J("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName||ue(this.tableName??"",S(this.columnNode.column))})),this)}check(t,e){let r=S(this.columnNode.column),o=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new J("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new J("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new Ir(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.nodes.push(new J("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Je=class extends Ke{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new $r(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new $(e)}char(e,r=1){let o=new B(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new B(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new B(e,r);return this.build(o)}longtext(e){return this.text(e,"longtext")}mediumtext(e){return this.text(e,"mediumtext")}tinytext(e){return this.text(e,"tinytext")}uuid(e){let r=new B(e,"uuid");return this.build(r)}ulid(e){let r=new B(e,"ulid");return this.build(r)}integer(e,r=255){let o=new B(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new B(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new B(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new B(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new B(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new B(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new B(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new B(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new B(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new B(e,"numeric",{precision:r,scale:o});return this.build(n)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let o=new B(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new B(e,"time",{precision:r});return this.build(o)}year(e){let r=new B(e,"year");return this.build(r)}datetime(e,r){let o=new B(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}timestamp(e,r){let o=new B(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}boolean(e){let r=new B(e,"boolean");return this.build(r)}binary(e){let r=new B(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new B(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new B(e,"blob");return this.build(r)}tinyblob(e){let r=new B(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new B(e,"mediumblob");return this.build(r)}longblob(e){let r=new B(e,"longblob");return this.build(r)}json(e){let r=new B(e,"json");return this.build(r)}jsonb(e){let r=new B(e,"jsonb");return this.build(r)}enum(e,r){let o=new B(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new B(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new B(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new B(e,"geometry");return this.build(r)}point(e){let r=new B(e,"point");return this.build(r)}linestring(e){let r=new B(e,"linestring");return this.build(r)}polygon(e){let r=new B(e,"polygon");return this.build(r)}multiPoint(e){let r=new B(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Pr=class extends Ke{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new $(t)}addColumn(t){let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(p=>p.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(p=>{let c=p;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),u=new Jt(a);u.inlineConstraints=l,this.nodes.push(u),o.getNodes().filter(p=>{let c=p;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(p=>{this.nodes.push(new be(p));});}alterColumn(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(m=>m.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=S(s.column),l=o.getNodes().find(m=>m.constraintType==="null"),d=o.getNodes().find(m=>m.constraintType==="not_null")||l,p=o.getNodes().find(m=>m.constraintType==="default"),c={};d&&(c.nullable=d.constraintType==="null"),p&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?c.dropDefault=true:c.default=p.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(c.collate=s.collate),this.nodes.push(new Ht(S(a),s,c)),d&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(d.constraintType==="not_null"?this.nodes.push(new Xt(S(a))):d.constraintType==="null"&&this.nodes.push(new Yt(S(a)))),p&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(p.defaultValue===void 0||p.defaultValue===null||p.defaultValue==="NULL"?this.nodes.push(new bt(S(a))):this.nodes.push(new Zt(S(a),p.defaultValue))),o.getNodes().forEach(m=>{let g=m;switch(g.constraintType){case "primary_key":this.addPrimaryKey(S(a));break;case "unique":this.unique(S(a),{constraintName:g.constraintName});break;case "foreign_key":this.foreignKey(S(a),g.references?.table??"",S(g.references?.columns?.[0]??""),{constraintName:g.constraintName,onDelete:g.onDelete,onUpdate:g.onUpdate});break}});}dropColumn(t){this.nodes.push(new zt(t));}renameColumn(t,e){this.nodes.push(new Gt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new bt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new nt([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(new J(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(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 h("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(new J("unique",{columns:[t],constraintName:e?.constraintName??ue(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new h("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 we(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new h("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 we(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new we(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new h("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new h("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new st(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",o=this.sqlType==="mssql",n=this.sqlType==="oracledb";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new We(t)):r?this.nodes.push(new We(t)):o?this.nodes.push(new We(t)):n&&this.nodes.push(new We(t)),this)}};var le=class{constructor(t){if(this.sqlType=t||I.DB_TYPE,!this.sqlType)throw new h("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new $(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!Wr.existsSync(t))throw new h("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=mt.basename(t),r=mt.extname(e);if(r!==".sql"&&r!==".txt")throw new h("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=Wr.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new Je(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new T({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?o.getMysqlOptions()||{}:{}},l=new er(t,n,o.getNamedConstraints(),r?.ifNotExists,a),u=s.parse([l]).sql,d=u.startsWith("create table")?u:`create table ${u}`;this.rawQuery(d),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new Pr(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 u=new Te(t,s),d=n.parse([u]).sql;if(!d||!d.trim())return;let p=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(p),s=[];};for(let u of r)u.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(u);a();let l=r.filter(u=>u.file==="add_column").map(u=>u.column);this.generateAutoUpdateTriggers(t,l);}dropTable(t,e=false){let r=new tr(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new Te(t,[new Ye(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new at(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||kt(t,e.join("_")),n=new or(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new nr(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new nt(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addUnique(t,e,r){let o=Array.isArray(e)?e:[e],n=r?.constraintName??ue(t,o.join("_")),s=new J("unique",{columns:o,constraintName:n}),a=new Te(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=z(t,e,r),n=new we(o),s=new Te(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 we(n),a=new Te(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new st,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new J(...e),o=new Te(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 we(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addCheck(t,e,r){let o=r?.constraintName??`chk_${t}_custom`.substring(0,63),n=new J("check",{checkExpression:e,constraintName:o}),s=new Te(t,[new be(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new we(e),o=new Te(t,[r]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}createExtension(t,e=true){let r=new rr(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(o=>o.folder==="column"&&o.autoUpdate===true).map(o=>S(o.column));for(let o of r){let n=this.getAutoUpdateTriggerSql(t,o);for(let s of n)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];case "oracledb":return [`CREATE OR REPLACE TRIGGER "${r}" BEFORE UPDATE ON "${t}" FOR EACH ROW BEGIN :NEW."${e}" := CURRENT_TIMESTAMP; END;`];default:return []}}generateAstInstance(t){return new T(t,this.sqlType)}};var Er,Kp,At=class{constructor(t,e){ul(this,Er);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new le(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=dl(this,Er,Kp).call(this)),this.executionPromise.then(t,e)}rawStatement(t){return this.schema.rawStatement(t)}rawQuery(t){return this.schema.rawQuery(t),this}createTable(t,e,r){return this.schema.createTable(t,e,r),this}alterTable(t,e){return this.schema.alterTable(t,e),this}dropTable(t,e=false){return this.schema.dropTable(t,e),this}renameTable(t,e){return this.schema.renameTable(t,e),this}truncateTable(t){return this.schema.truncateTable(t),this}createIndex(t,e,r){return this.schema.createIndex(t,e,r),this}dropIndex(t,e){return this.schema.dropIndex(t,e),this}addPrimaryKey(t,e){return this.schema.addPrimaryKey(t,e),this}addUnique(t,e,r){return this.schema.addUnique(t,e,r),this}addConstraint(t,e,...r){return this.schema.addConstraint(t,e,...r),this}dropPrimaryKey(t){return this.schema.dropPrimaryKey(t),this}dropForeignKey(t,e,r){return this.schema.dropForeignKey(t,e,r),this}dropUnique(t,e,r){return this.schema.dropUnique(t,e,r),this}dropConstraint(t,e){return this.schema.dropConstraint(t,e),this}createExtension(t,e=true){return this.schema.createExtension(t,e),this}toQuery(){let t=this.schema.queryStatements;return t.length===1?t[0]:t}toQueries(){return [...this.schema.queryStatements]}toString(){let t=this.schema.queryStatements;return t.length===1?t[0]||"":t.join(`;
|
|
193
|
+
`)}async execute(){if(this.state!=="executed"){if(this.state==="failed")throw this.executionError;return this.then()}}isExecuted(){return this.state==="executed"}isPending(){return this.state==="pending"}hasFailed(){return this.state==="failed"}};Er=new WeakSet,Kp=async function(){try{this.state="pending";let t=this.schema.queryStatements;if(!t.length){this.state="executed";return}for(let e of t)await this.dataSource.rawQuery(e);this.state="executed";}catch(t){throw this.state="failed",this.executionError=t,t}};var vr=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 u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===n.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(u=>u.table===n.table);if(l){let u=l.getColumns().find(d=>d.databaseName===n.column);if(u){u.isPrimary&&a.push(`pk.${n.table}`);let d=l.getRelations();for(let p of d)p.columnName===u.columnName&&a.push(`fk.${n.table}.${p.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let u of l)s(u);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("."),u=t.relationsToDrop?.find(d=>d.table===a&&d.relation.name===l);u&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:u,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(u)});}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 u of l)u.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)}):u.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(u=>u.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Br=class Br{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new vr(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 u=r(l);return u?!(s.has(u)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new le(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===o.table)?.getColumns().find(u=>u.columnName===o.columns[0])?.primaryKeyConstraintName||ye(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,u=>{let d=a||ye(o.table,o.columns[0]);u.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}for(let o of t.checksToDrop||[]){let n=new le(this.sql.getDbType());n.dropCheck(o.table,o.name);let s=n.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}for(let o of t.checksToAdd||[]){let n=new le(this.sql.getDbType());n.addCheck(o.table,o.expression,{constraintName:o.name});let s=n.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=S(t.relation.constraintName);if(e)return e;let r=t.table;t.relation.type==="belongsTo"?r=t.relation.model().table:t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(r=S(t.relation.manyToManyOptions.throughModel));let n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,z(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=S(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s;if(Array.isArray(r.type))s=e.enum(o[0],r.type);else if(typeof r.type=="string"&&Br.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...o);else if(typeof r.type=="string")s=e.custom(o[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||ye(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new le(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=S(t.relation.manyToManyOptions.throughModel),r=S(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let o=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,n=S(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),m=c.primaryKey,f=c.getColumns().find(b=>b.columnName===m);if(f)n=f.databaseName;else {let b=c?.databaseCaseConvention||"preserve";n=V(m,b);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let m=c.getColumns(),g=m.find(f=>f.columnName===n);if(g)n=g.databaseName;else {let f=c.primaryKey||"id",b=m.find(w=>w.columnName===f);if(b)n=b.databaseName;else {let w=c?.databaseCaseConvention||"preserve";n=V(n||f,w);}}}else {let m=c.primaryKey||"id",f=c.getColumns().find(b=>b.columnName===m);if(f)n=f.databaseName;else {let b=c?.databaseCaseConvention||"preserve";n=V(m,b);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(c=>c.columnName===l);if(u)l=u.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=V(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(m=>m.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=V(t.relation.foreignKey,m);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,m=S(c),g=a.find(f=>f.columnName===m);if(g)l=g.databaseName;else {let f=s?.databaseCaseConvention||"preserve";l=V(m,f);}}let d=t.relation.onDelete?.toLowerCase(),p=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,c=>{let m=o||z(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:m,onDelete:d,onUpdate:p});}).toQueries()}formatSqlStatements(t){return t.map(e=>({...e,sqlStatements:e.sqlStatements.map(r=>format(r,{...this.sql.inputDetails.queryFormatOptions}).replace(/\n/g," ").replace(/\s+/g," "))}))}};Br.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var xt=Br;var Qr=class Qr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],o=null,n={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==o&&(o=s.phase,e.length>0&&e.push(""),e.push(`// ${n[o]}`));let{up:a,down:l}=this.generateOperationCode(s);a&&e.push(...a),l&&r.push(...l);}return {up:e,down:r}}generateOperationCode(t){switch(t.type){case "CREATE_TABLE":return this.generateCreateTableCode(t);case "ADD_COLUMN":return this.generateAddColumnCode(t);case "MODIFY_COLUMN":return this.generateModifyColumnCode(t);case "DROP_COLUMN":return this.generateDropColumnCode(t);case "CREATE_INDEX":return this.generateCreateIndexCode(t);case "DROP_INDEX":return this.generateDropIndexCode(t);case "ADD_FOREIGN_KEY":return this.generateAddForeignKeyCode(t);case "DROP_FOREIGN_KEY":return this.generateDropForeignKeyCode(t);case "ADD_UNIQUE_CONSTRAINT":return this.generateAddUniqueCode(t);case "DROP_CONSTRAINT":return this.generateDropConstraintCode(t);case "ADD_CHECK_CONSTRAINT":return this.generateAddCheckCode(t);case "ADD_PRIMARY_KEY":return this.generateAddPrimaryKeyCode(t);case "DROP_TABLE":return this.generateDropTableCode(t);case "MODIFY_PRIMARY_KEY":return this.generateModifyPrimaryKeyCode(t);default:return {up:null,down:null}}}generateCreateTableCode(t){let e=t.data,r=[];r.push(`this.schema.createTable(${this.quote(e.table)}, (table) => {`);for(let n of e.columns){let s=this.generateColumnCode(e.table,n,true);r.push(` ${s}`);}r.push("});");let o=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:o}}generateAddColumnCode(t){let{table:e,column:r}=t.data,o=this.generateColumnCode(e,r,false),n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:n,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:o}=t.data,n=this.generateColumnCodeForModify(e,r,o),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(o.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],n=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:o,down:n}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(p=>p.columnName===u)?.databaseName||u),s=n.length===1?this.quote(n[0]):`[${n.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.createIndex(${this.quote(e.table)}, ${s}, { constraintName: ${this.quote(e.index)} });`],l=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`];return {up:a,down:l}}generateDropIndexCode(t){let e=t.data,r=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`],o=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:o}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:o,referencedColumn:n,constraintName:s}=this.resolveRelationDetails(e),a=e.relation.onDelete?.toLowerCase(),l=e.relation.onUpdate?.toLowerCase(),u=[];s&&u.push(`constraintName: ${this.quote(s)}`),a&&u.push(`onDelete: ${this.quote(a)}`),l&&u.push(`onUpdate: ${this.quote(l)}`);let d=u.length>0?`, { ${u.join(", ")} }`:"",p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(o)}, ${this.quote(n)}${d});`,"});"],c=s||z(e.table,r,o),m=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(c)});`,"});"];return {up:p,down:m}}generateDropForeignKeyCode(t){let e=t.constraint||t.data?.relation?.name;if(!e)return {up:null,down:null};let r=t.table||t.data?.table,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],n=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:o,down:n}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=`[${(e.columns||[]).map(u=>r?.getColumns().find(p=>p.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,o=t.constraint||e.name;if(!o||!r)return {up:null,down:null};if(e.type==="primary_key"){let a=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});"],l=[`// TODO: reverse primary key drop on ${this.quote(r)}`];return {up:a,down:l}}if(e.type==="unique"){let a=e.column,l=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],u=[`// TODO: reverse unique constraint drop for ${this.quote(a)} on ${this.quote(r)}`];return {up:l,down:u}}if(e.expression!==void 0){let a=[`this.schema.dropCheck(${this.quote(r)}, ${this.quote(o)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:a,down:l}}let n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:n,down:s}}generateAddCheckCode(t){let e=t.data,r=[`this.schema.addCheck(${this.quote(e.table)}, ${this.quote(e.expression)}, { constraintName: ${this.quote(e.name)} });`],o=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:o}}generateAddPrimaryKeyCode(t){let e=t.data,n=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||ye(e.table,e.columns[0]),s=`[${e.columns.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.addConstraint("primary_key", { columns: ${s}, constraintName: ${this.quote(n)} });`,"});"],l=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`," table.dropPrimaryKey();","});"];return {up:a,down:l}}generateDropTableCode(t){let e=t.table||t.data?.table,r=[`this.schema.dropTable(${this.quote(e)});`],o=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:o}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],n=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:o,down:n}}generateColumnCode(t,e,r){let o=this.generateColumnTypeCode(e);if(!r)return o;if(e.isPrimary){let n=e.primaryKeyConstraintName||ye(t,e.columnName);o+=`.primaryKey({ constraintName: ${this.quote(n)} })`;}return e.unsigned&&(o+=".unsigned()"),e.zerofill&&(o+=".zerofill()"),e.constraints?.default!==void 0&&(o+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o+";"}generateColumnCodeForModify(t,e,r){let o=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?o+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&(o+=".default(null)"),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o}generateColumnTypeCode(t){let e=t.databaseName;if(Array.isArray(t.type)){let s=t.type.map(a=>this.quote(a)).join(", ");return `table.enum(${this.quote(e)}, [${s}])`}let r=t.type;if(new Set(["uuid","ulid","boolean","year","json","jsonb","binary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]).has(r))return `table.${r}(${this.quote(e)})`;if(r==="timestamp"||r==="datetime"){let s=[];return t.withTimezone&&s.push("withTimezone: true"),t.precision!=null&&s.push(`precision: ${t.precision}`),s.length>0?`table.${r}(${this.quote(e)}, { ${s.join(", ")} })`:`table.${r}(${this.quote(e)})`}return r==="date"||r==="time"?t.precision!=null?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="increment"||r==="bigIncrement"?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:r==="decimal"||r==="numeric"?t.precision!=null?t.scale!=null?`table.${r}(${this.quote(e)}, ${t.precision}, ${t.scale})`:`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="float"||r==="double"||r==="real"?t.precision!=null&&t.precision!==10?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="longtext"||r==="mediumtext"||r==="tinytext"?`table.${r}(${this.quote(e)})`:new Set(["varchar","char","string","integer","tinyint","smallint","mediumint","bigint","biginteger","varbinary"]).has(r)?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:Qr.BUILTIN_COLUMN_TYPES.has(r)?`table.${r}(${this.quote(e)})`:t.length!=null?`table.custom(${this.quote(e)}, ${this.quote(r)}, ${t.length})`:`table.custom(${this.quote(e)}, ${this.quote(r)})`}resolveRelationDetails(t){let e=t.table,r="id";if(t.relation.type==="belongsTo"){let l=t.relation.model();e=l.table;let u=l.primaryKey||"id";r=l.getColumns().find(c=>c.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=S(t.relation.manyToManyOptions.throughModel);let l=S(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let n=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=n.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=S(t.relation.manyToManyOptions.leftForeignKey);s=n.find(d=>d.columnName===l)?.databaseName||l;}else s=n.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName:S(t.relation.constraintName)||void 0;return {sourceColumn:s,referencedTable:e,referencedColumn:r,constraintName:a}}quote(t){return `"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}formatDefaultValue(t){return t==null?"null":t==="NULL"?'"NULL"':typeof t=="boolean"||typeof t=="number"?t.toString():t==="TRUE"||t==="true"?"true":t==="FALSE"||t==="false"?"false":this.quote(String(t))}};Qr.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var Kr=Qr;function yy(i){return i.replace(/\s+/g," ").trim()}function hy(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Qe(i,t){let e=yy(t.toLowerCase()),r=hy(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var kr=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql._models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(f=>f?.type!==void 0&&f?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let w of n.indexes)o.indexes.map(q=>q.name).includes(w.name)||e.data.indexesToAdd.push({table:r.table,index:w.name});let f=r.getUniques?.()||[];for(let w of f)e.data.uniquesToAdd.push({table:r.table,name:w.name||"mandatory",columns:w.columns});let b=r.getChecks?.()||[];for(let w of b)e.data.checksToAdd.push({table:r.table,name:w.name,expression:w.expression});for(let w of n.relations){if(w.type!=="belongsTo")continue;let q=S(w.constraintName);o.foreignKeys.find(R=>R.name===q)||e.data.relationsToAdd.push({table:r.table,relation:w,onDelete:w.onDelete,onUpdate:w.onUpdate});}return}for(let f of n.columns)o.columns.some(w=>w.name===f.databaseName||w.name===f.columnName)||e.data.columnsToAdd.push({table:r.table,column:f});let s=r.getColumns();for(let f of o.columns)s.some(w=>w.databaseName===f.name||w.columnName===f.name)||e.data.columnsToDrop.push({table:r.table,column:f.name});for(let f of n.indexes)o.indexes.map(b=>b.name).includes(f.name)||e.data.indexesToAdd.push({table:r.table,index:f.name});let a=r.getUniques?.()||[];for(let f of a)o.indexes.some(w=>w.name===f.name&&w.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:f.name||"mandatory",columns:f.columns});let l=o.foreignKeys.map(f=>f.name);for(let f of o.indexes)f.isUnique||l.includes(f.name)||n.indexes.map(w=>w.name).includes(f.name)||e.data.indexesToDrop.push({table:r.table,index:f.name});for(let f of o.indexes){if(!f.isUnique||f.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(w=>w.name).includes(f.name)||e.data.uniquesToDrop.push({table:r.table,name:f.name});}let u=r.getChecks?.()||[];for(let f of u)o.checkConstraints.some(w=>w.name===f.name)||e.data.checksToAdd.push({table:r.table,name:f.name,expression:f.expression});let d=new Set(u.map(f=>f.name)),p=n.columns.filter(f=>Array.isArray(f.type)),c=new Set(p.map(f=>f.databaseName||f.columnName));for(let f of o.checkConstraints)if(!d.has(f.name)){let b=[...c].find(w=>new RegExp(`[\\["\\[]?${w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i").test(f.expression));if(b){let w=p.find(M=>(M.databaseName||M.columnName)===b),q=o.columns.find(M=>M.name===b);if(w&&q?.enumValues&&Array.isArray(w.type)){let M=[...w.type].sort(),R=[...q.enumValues].sort();if(!(M.length===R.length&&M.every((D,C)=>D===R[C]))){e.data.checksToDrop.push({table:r.table,name:f.name});let D=e.sql.getDbType(),C=D==="mssql"?"[":'"',v=D==="mssql"?"]":'"',re=w.type.map(P=>`'${P.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:f.name,expression:`${C}${b}${v} IN (${re})`});}}}else e.data.checksToDrop.push({table:r.table,name:f.name});}for(let f of n.columns){let b=o.columns.find(M=>M.name===f.databaseName||M.name===f.columnName);if(!b)continue;let w=!e.areColumnsEqual(b,f,o.indexes),q=e.getDefaultChange({table:r.table,dbColumns:b,modelColumn:f});(w||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:b,modelColumn:f});}for(let f of n.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;if(f.type==="manyToMany"&&f.manyToManyOptions){let q=S(f.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:S(f.manyToManyOptions.leftForeignKey),foreignKey:f.manyToManyOptions.leftForeignKey,constraintName:f.constraintName?S(f.constraintName):z(q,S(f.manyToManyOptions.leftForeignKey||De(r.table)),r.table),onDelete:f.onDelete,onUpdate:f.onUpdate},onDelete:f.onDelete,onUpdate:f.onUpdate});continue}let b=S(f.constraintName);if(b&&o.foreignKeys.some(q=>q.name===b))continue;o.foreignKeys.find(q=>e.relationMatchesDbRelation(r,f,q))||e.data.relationsToAdd.push({table:r.table,relation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let m=new Set(n.relations.filter(f=>f.type==="belongsTo").map(f=>{let b=S(f.foreignKey)||f.columnName,q=r.getColumns().find(M=>M.columnName===b)?.databaseName||b;return S(f.constraintName)||z(r.table,q,f.model().table)}));for(let f of o.foreignKeys){if(f.name&&m.has(f.name))continue;n.relations.find(w=>w.type!=="belongsTo"&&w.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,w,f))||e.data.relationsToDrop.push({table:r.table,relation:f});}for(let f of n.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;let b=o.foreignKeys.find(w=>e.relationMatchesDbRelation(r,f,w));b&&!e.areRelationsEqual(b,f)&&e.data.relationsToModify.push({table:r.table,dbRelation:b,modelRelation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let g=r.primaryKey;if(g&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[g]}),o.primaryKey&&!g&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),g&&o.primaryKey){let f=r.getColumns().find(b=>b.columnName===g);f&&!e.arePrimaryKeysEqual(o.primaryKey,f)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:g});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getCodeStatements(){let e=new xt(this.sql).generateOperations(this.data);return new Kr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new xt(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=Qe(n,t.dataType),a=typeof e.type=="string"?Qe(n,e.type):void 0;if(a&&o&&(o=s===a),Array.isArray(e.type)&&(n==="mysql"||n==="mariadb")){let u=[...e.type].sort(),d=t.enumValues?[...t.enumValues].sort():null;d&&o&&(o=u.length===d.length&&u.every((p,c)=>p===d[c]));}e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let u=e.constraints.nullable,d=t.isNullable;o=o&&u===d;}if(n==="mysql"||n==="mariadb"){if(e.unsigned!==void 0||t.unsigned!==void 0){let u=e.unsigned??false,d=t.unsigned??false;o&&(o=u===d);}if(e.zerofill!==void 0||t.zerofill!==void 0){let u=e.zerofill??false,d=t.zerofill??false;o&&(o=u===d);}}return o}areRelationsEqual(t,e){let r=S(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",p=u.getColumns().find(g=>g.columnName===d),c=u.table,m=p?.databaseName||d;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===m;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=S(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===u;}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 f=n.model();f&&f.table&&(o=f);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?S(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=S(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),d=(n.type||"belongsTo")==="belongsTo"?S(n.foreignKey):n.columnName,p=l.find(f=>f.columnName===d);p&&(d=p.databaseName);let c=o.primaryKey||"id",g=o.getColumns().find(f=>f.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===g}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Qe(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Qe(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",u=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&u?false:"drop";if(s&&a){let d=String(t.dbColumns.defaultValue),p=String(t.modelColumn.constraints?.default),c=this.normalizeDefaultValue(e,r,d),m=this.normalizeDefaultValue(e,o||r,p);return c!==m?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=S(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(P=>P.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find(P=>P.columnName===l),p=a.getColumns().find(P=>P.columnName===u);if(!d||!p)continue;let c=S(o.manyToManyOptions.leftForeignKey)||l,m=S(o.manyToManyOptions.rightForeignKey)||u,g=await this.sql.getTableSchema(n);if(!g.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(d,c),this.clonePkAsColumn(p,m)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:m,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let f=this.clonePkAsColumn(d,c),b=this.clonePkAsColumn(p,m),w=g.columns.find(P=>P.name===c),q=g.columns.find(P=>P.name===m),M=w?this.areColumnsEqual(w,f,g.indexes):false,R=q?this.areColumnsEqual(q,b,g.indexes):false;for(let P of g.foreignKeys){let X=P.referencedTable===s.table,ee=P.referencedTable===a.table;if(!X&&!ee)continue;let Re=X?c:m,xe=P.columns[0];xe&&xe!==Re&&(this.data.relationsToDrop.push({table:n,relation:P}),xe!==c&&xe!==m&&this.data.columnsToDrop.push({table:n,column:xe}));}let A={};M||(A[f.databaseName]=f),R||(A[b.databaseName]=A[b.databaseName]||b);for(let P of Object.keys(A))this.data.columnsToAdd.push({table:n,column:A[P]});let D=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),C=this.buildBelongsToRelation(n,o.model,m,u,void 0,o.onDelete,o.onUpdate),v=g.foreignKeys.find(P=>P.referencedTable===s.table&&P.columns.length===1&&P.columns[0]===c),re=g.foreignKeys.find(P=>P.referencedTable===a.table&&P.columns.length===1&&P.columns[0]===m);if(!v){let P=g.foreignKeys.find(X=>X.referencedTable===s.table);P&&this.data.relationsToDrop.push({table:n,relation:P}),this.data.relationsToAdd.push(D);}if(!re){let P=g.foreignKeys.find(X=>X.referencedTable===a.table);P&&this.data.relationsToDrop.push({table:n,relation:P}),this.data.relationsToAdd.push(C);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,p=S(a.constraintName)||z(o.table,d,a.model().table);s.add(p);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(f=>f.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(b=>b.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(b=>b.columnName===l)?.databaseName||l;let u=o.table,d=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let f=o.relation.model();u=f.table;let b=f.primaryKey||"id";d=f.getColumns().find(q=>q.columnName===b)?.databaseName||b;}let p=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(f=>{if(f.columns.length!==1||f.referencedColumns.length!==1)return false;let b=p.has(f.columns[0]),w=f.referencedTable===u,q=f.referencedColumns[0]===d;return b&&w&&q}),m=S(o.relation.constraintName)||z(o.table,l,u),g=e.get(o.table)||new Set;if(c||m&&g.has(m))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let f=S(o.relation.manyToManyOptions.throughModel),b=S(o.relation.manyToManyOptions.leftForeignKey),w=S(o.relation.manyToManyOptions.rightForeignKey),q=o.table===f&&o.relation.columnName===b&&o.relation.model().table===s?.table,M=o.table===f&&o.relation.columnName===w&&o.relation.model().table!==s?.table,R=await this.sql.getTableSchema(f),A=R.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===b&&C.referencedTable===(s?.table||"")),D=R.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===w&&C.referencedTable===o.relation.model().table);if(q&&A||M&&D)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(u=>u.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let p=a.find(b=>b.columnName===u.foreignKey)?.databaseName||u.foreignKey,c=u.model(),m=c.primaryKey||"id",f=c.getColumns().find(b=>b.columnName===m)?.databaseName||m;return o.relation.columns.length===1&&o.relation.columns[0]===p&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===f})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?S(n):z(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var kp=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??He()});var gy=async i=>(await pe.getDriver(i)).client,Lr=async(i,t)=>{let e=await gy(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 u=e,d=t,p=d?.database;return new u.Database(p,d?.driverOptions?.mode??void 0,D=>{if(D)throw new h("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let m=e,g=t,{options:f,...b}=g.driverOptions??{},w=new m.ConnectionPool({server:g.host??"localhost",port:g.port,database:g.database,user:g.username,password:g.password,...b,options:{trustServerCertificate:I.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...f,abortTransactionOnError:false,enableImplicitTransactions:false}});return await w.connect(),w;case "oracledb":let q=e,M=t,R=`${M.host}/${M.database}`;return await q.createPool({user:M.username,password:M.password,connectString:R,...M.driverOptions});default:throw new h("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var Dt=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Me.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await t(e);return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),oe("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;oe("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new h("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");_.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw _.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new h("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");_.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 h("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new h("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw _.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 h("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){_.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new h("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 h("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 _.error(e),new k("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 h("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var el=Symbol.for("hysteria.orm.SqlDataSource"),Lp,Wp,ct=class i extends(Wp=ut,Lp=el,Wp){constructor(e){super(e);this[Lp]=true;this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new yr;this.migrationConfig={path:I.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:yt(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 i(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&el in e&&e[el]===true}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static async useConnection(e,r){let o=new i(e);await o.connect();try{await r(o),o.isConnected&&await o.disconnect();}catch(n){throw o.isConnected&&await o.disconnect(),n}}async connect(){if(this.isConnected)throw new h("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await Lr(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await Lr(e.sqlType,e.inputDetails),e.ownsPool=true;}));}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){let e=this;return new Proxy(this._models,{get(r,o){if(typeof o=="string"&&o in r)return e.from(r[o])}})}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 h("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new h("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,u=[];a?(l=r,u=o):(l=void 0,u=r!==void 0?[r,...o]:o);let d=Za(JSON.stringify(u)),p=d?`${e}:${d}`:e,c=await this.cacheAdapter.get(p);if(c!==void 0)return c;let m=await n(...u);return await this.cacheAdapter.set(p,m,l),m}async invalidCache(e,...r){if(!this.cacheAdapter)throw new h("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new h("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=Za(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new h("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await Lr(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this;if(typeof e=="string"){let n=new K(kp(e,r),o);return r?.alias&&n.table(e,r.alias),n}return new Pe(e,o)}schema(){if(!this.isConnected)throw new h("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new At(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new Dt(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new h("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){_.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new Dt(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{let a=await e(s);return await s.commit({throwErrorOnInactiveTransaction:!1}),a}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected)throw new h("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new $e(e,this.globalTransaction.sql):new $e(e,this)}getPool(){if(!this.sqlPool)throw new h("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new h("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 h("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){oe("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{_.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){_.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),oe("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new h("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){_.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await kr.makeDiff(this)).getSqlStatements();if(!o.length){_.info("No new changes detected between database schema and models metadata");return}if(_.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);_.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),_.info(`Synced schema with ${o.length} SQL statements`);}extractRowsFromRawResult(e){let r=this.getDbType();if(r==="mysql"||r==="mariadb"){if(Array.isArray(e)&&e.length>=1){let o=e[0];if(Array.isArray(o))return o;if(typeof o=="object"&&o!==null&&("insertId"in o||"affectedRows"in o))return []}return e}return r==="postgres"||r==="cockroachdb"?e&&typeof e=="object"&&"rows"in e?e.rows||[]:e:Array.isArray(e)?e:[]}async rawQuery(e,r=[],o){if(!this.isConnected)throw new h("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async s=>H(e,r,s,this.getDbType(),"raw")):H(e,r,this,this.getDbType(),"raw")}rawStatement(e){return new $(e)}async getTableSchema(e){let[r,o,n,s,a]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e),this.getCheckConstraintInfo(e)]),l=this.getDbType();if(l==="postgres"||l==="mssql")for(let u of r){let d=a.find(p=>{let c=p.expression;return new RegExp(`[\\["\\[]?${u.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(([^)]+)\\)`,"i").test(c)});if(d){let p=new RegExp("IN\\s*\\(([^)]+)\\)","i"),c=d.expression.match(p);c&&(u.enumValues=c[1].split(",").map(m=>m.trim().replace(/^'|'$/g,"")));}}return {columns:r,indexes:o,foreignKeys:n,primaryKey:s,checkConstraints:a}}getModelOpenApiSchema(){return Ep(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new h("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Ya(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new h("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await Pp(this,this.adminJsOptions),this.adminJsInstance)}getAdminJs(){return this.adminJsInstance}getAdminJsOptions(){return this.adminJsOptions}isAdminJsEnabled(){return !!this.adminJsOptions?.enabled}async getTableInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Dr(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(Ze(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),u=Qe(s,l);return {name:a.name,dataType:u,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||""),u=String(a.data_type||a.DATA_TYPE||a.type||"").toLowerCase(),d=Qe(s,u),p=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof p=="string"?p.toLowerCase()!=="no":typeof p=="boolean"?p:a.notnull!==void 0?a.notnull===0:true,m=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,g=a.char_length!=null?Number(a.char_length):null,f=a.numeric_precision!=null?Number(a.numeric_precision):null,b=a.numeric_scale!=null?Number(a.numeric_scale):null,w=a.timezone!=null?!!a.timezone:/with time zone/.test(String(a.column_type||a.udt_name||u||"").toLowerCase()),q=null,M=String(a.column_type||a.COLUMN_TYPE||""),R=M.match(/^enum\((.+)\)$/i);R&&(q=R[1].split(",").map(v=>v.trim().replace(/^'|'$/g,"")));let A=M.toLowerCase(),D=A.includes(" unsigned"),C=A.includes(" zerofill");return {name:l,dataType:d,isNullable:c,defaultValue:m,length:g,precision:f,scale:b,withTimezone:w,enumValues:q,unsigned:D,zerofill:C}})}async getIndexInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Ar(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(Ze(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let u of s){let d=u.Key_name,p=u.Non_unique===0,c=l.get(d)||{name:d,columns:[],isUnique:p};c.columns.push(u.Column_name),l.set(d,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let u of s){let d=u.index_name,p=!!u.is_unique,c=l.get(d)||{name:d,columns:[],isUnique:p};c.columns.push(u.column_name),l.set(d,c);}return Array.from(l.values())}let a=[];for(let l of s){let u=l.name,d=!!l.unique,p=await this.rawQuery(`PRAGMA index_info(${u})`),m=this.extractRowsFromRawResult(p).map(g=>g.name);a.push({name:u,columns:m,isUnique:d});}return a}async getForeignKeyInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Or(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Ze(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let u of n){let d=Number(u.id),p=l.get(d)||{name:void 0,columns:[],referencedTable:String(u.table),referencedColumns:[],onDelete:u.on_delete??null,onUpdate:u.on_update??null};p.columns.push(String(u.from)),p.referencedColumns.push(String(u.to)),l.set(d,p);}return Array.from(l.values())}let a=new Map;for(let l of n){let u=String(l.name||""),d=u||`${l.referenced_table}_${l.column_name}`,p=a.get(d)||{name:u||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};p.columns.push(String(l.column_name)),p.referencedColumns.push(String(l.referenced_column)),a.set(d,p);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new xr(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Ze(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async getCheckConstraintInfo(e){let o=new T({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new _r(e)]).sql,n=[];try{let s=await this.rawQuery(o);n=this.extractRowsFromRawResult(s);}catch(s){if(Ze(this.getDbType(),s))return [];throw s}return n.map(s=>({name:String(s.name),expression:String(s.expression)}))}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
|
|
194
194
|
v_result NUMBER;
|
|
195
195
|
BEGIN
|
|
196
196
|
v_result := DBMS_LOCK.REQUEST(
|
|
@@ -213,7 +213,7 @@ Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]
|
|
|
213
213
|
ELSE
|
|
214
214
|
:result := 0;
|
|
215
215
|
END IF;
|
|
216
|
-
END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return _.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return _.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return _.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}}};var
|
|
216
|
+
END;`))?.outBinds?.result===1}catch(o){let n=o instanceof Error?o:new Error(String(o));return _.warn(`Oracle lock release may have failed: ${n.message}`),!1}case "sqlite":return !0;default:return _.warn(`Advisory locks not implemented for database type: ${r}`),!0}}catch(o){let n=o instanceof Error?o:new Error(String(o));return _.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}}};var tl=class{constructor(t){this.dbType=t,this.migrationName=mt.basename(fileURLToPath(import.meta.url)),this.schema=new le(this.dbType);}};async function qy(i){try{return import(pathToFileURL(i).href)}catch{let e=createRequire(import.meta.url)(i);return {default:e.default||e,...e}}}async function Cy(i){let{build:t}=await import('esbuild').catch(()=>{throw new Error("esbuild is required to import TypeScript files. Install it with: npm install esbuild -D")}),e=Math.random().toString(36).slice(2,8),r=i.replace(/\.ts$/,`.bundled_${e}.mjs`);try{return await t({entryPoints:[i],bundle:!0,platform:"node",format:"esm",sourcemap:"inline",outfile:r,packages:"external",logLevel:"silent"}),await import(pathToFileURL(r).href)}finally{await Wr.promises.unlink(r).catch(()=>{});}}async function Up(i,t){let e=mt.isAbsolute(i)?i:mt.resolve(process.cwd(),i);return e.endsWith(".ts")?Cy(e):qy(e)}var rl=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return r[0].map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.rows.map(n=>n.table_name);case "mssql":return r.recordset.map(n=>n.TABLE_NAME);case "oracledb":return (r.rows||[]).map(n=>Array.isArray(n)?n[0]:n?.TABLE_NAME).filter(n=>typeof n=="string"&&n.length>0);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
|
|
217
217
|
FROM information_schema.tables
|
|
218
218
|
WHERE table_catalog = '${e}'
|
|
219
219
|
AND table_schema = 'public'
|
|
@@ -327,5 +327,5 @@ CREATE TABLE [migrations] (
|
|
|
327
327
|
"id" NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
328
328
|
"name" VARCHAR2(255) NOT NULL,
|
|
329
329
|
"timestamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
|
|
330
|
-
)`}},
|
|
330
|
+
)`}},Ce=new rl;var _y=async(i,t)=>{if(i.endsWith(".ts"))return Up(i);try{return import(pathToFileURL(i).href)}catch{let o=createRequire(import.meta.url);try{let n=o(i);return {default:n.default||n,...n}}catch{throw new h(`MigrationUtils::importMigrationFile Failed to import migration file: ${i}. Both ESM and CommonJS imports failed.`,"MIGRATION_MODULE_NOT_FOUND")}}};async function jr(i,t){switch(i){case "mariadb":case "mysql":let e=t;return await e.query(Ce.migrationTableTemplateMysql()),(await e.query(Ce.selectAllFromMigrationsTemplate()))[0];case "postgres":case "cockroachdb":let o=t;return await o.query(Ce.migrationTableTemplatePg()),(await o.query(Ce.selectAllFromMigrationsTemplate())).rows;case "sqlite":return await Vp(Ce.migrationTableTemplateSQLite(),[],t),await Vp(Ce.selectAllFromMigrationsTemplate(),[],t)||[];case "mssql":let s=t;return await s.request().query(Ce.migrationTableTemplateMssql()),(await s.request().query(Ce.selectAllFromMigrationsTemplate())).recordset;case "oracledb":let u=await t.getConnection();try{try{await u.execute(Ce.migrationTableTemplateOracle());}catch(p){if(p.errorNum!==955)throw p}return ((await u.execute('SELECT * FROM "migrations"')).rows||[]).map(p=>({id:p[0],name:p[1],timestamp:p[2]}))}finally{await u.close();}default:throw new h("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function Fr(i,t,e){let r=Ay(t),o=[];for(let{name:n,fullPath:s}of r){let a=await Oy(s),l=new a(i||I.DB_TYPE);l.migrationName=n,o.push(l);}return o}async function Oy(i,t){let e=await _y(i);if(!e.default)throw new h("MigrationUtils::loadMigrationModule Migration module does not have a default export","MIGRATION_MODULE_NOT_FOUND");return e.default}function Ay(i){let t=process.cwd(),e=i||I.MIGRATION_PATH||"database/migrations",r=/[*?{}\[\]]/.test(e);if(!r){let s=mt.isAbsolute(e)?e:mt.resolve(t,e);if(!Wr.existsSync(s))return Wr.mkdirSync(s,{recursive:true}),[]}let o=r?e:mt.join(e,"**/*.{ts,js}"),n=mt.isAbsolute(o)?o:mt.resolve(t,o);try{return Wr.globSync(n).filter(a=>Wr.statSync(a).isFile()).sort().map(a=>({name:mt.basename(a),fullPath:a}))}catch{return []}}async function Vp(i,t,e){return new Promise((r,o)=>{e.all(i,t,(n,s)=>{n&&o(n),r(s);});})}async function ol(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;_.info("Rolling back migrations for database type: "+n);try{let l=await jr(n,i.getPool()),u=await Fr(n,e,r),d=l.map(m=>m.name),p=u.filter(m=>d.includes(m.migrationName));if(p.length===0){_.info("No pending migrations.");return}if(t);let c=new ke(i);s&&(a=await i.transaction(),i=a.sql),await c.downMigrations(p),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}_.info("Migrations rolled back successfully");}async function nl(i,t,e,r,o){let n=i.getDbType(),s=o&&n!=="mssql"&&n!=="oracledb",a=null;_.info("Running migrations for database type: "+n);try{let l=await jr(n,i.getPool()),d=(await Fr(n,e,r)).filter(c=>!l.map(m=>m.name).includes(c.migrationName));if(!d.length){_.info("No pending migrations.");return}if(t);let p=new ke(i);s&&(a=await i.transaction(),i=a.sql),await p.upMigrations(d),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}_.info("Migrations ran successfully");}var ke=class{constructor(t){this.migrationTable="migrations";this.sql=t;}async upMigrations(t){for(let e of t){_.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){_.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.from(this.migrationTable).insert({name:t.migrationName,timestamp:r});}async deleteMigrationFromMigrationTable(t){await this.sql.from(this.migrationTable).where("name",t.migrationName).delete();}},sl=class{constructor(t=I.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){I.MIGRATION_PATH=this.migrationPath;let e;if(this.sqlDataSourceInput instanceof ct)e=this.sqlDataSourceInput;else {let r=this.sqlDataSourceInput;e=new ct(r),await e.connect();}return t==="up"?nl(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional):ol(e,void 0,this.migrationPath,e.migrationConfig.tsconfig,e.migrationConfig.transactional)}},xy=(i,t)=>new sl(i,t);var il=class{constructor(t){this.logger=_;this.sqlDataSource=t;}};function Dy(i){return {_phantom:void 0,_apply:i}}function pt(){return Dy((i,t)=>{Sr()(i,t);})}var Iy={string:()=>pt(),number:()=>pt(),boolean:()=>pt(),date:()=>pt(),object:()=>pt(),any:()=>pt()};function $y(i,t){let{properties:e,hooks:r}=t;class o extends dt{}o._collection=i;for(let[n,s]of Object.entries(e))s._apply(o.prototype,n);return r&&(r.beforeFetch&&(o.beforeFetch=r.beforeFetch),r.afterFetch&&(o.afterFetch=r.afterFetch),r.beforeInsert&&(o.beforeInsert=r.beforeInsert),r.beforeUpdate&&(o.beforeUpdate=r.beforeUpdate),r.beforeDelete&&(o.beforeDelete=r.beforeDelete)),o}export{il as BaseSeeder,dt as Collection,h as HysteriaError,yr as InMemoryAdapter,tl as Migration,Pe as ModelQueryBuilder,Ha as MongoDataSource,$ as RawNode,Op as RedisCacheAdapter,le as Schema,At as SchemaBuilder,ct as SqlDataSource,Z as WriteOperation,If as col,Ef as createSchema,$y as defineCollection,xy as defineMigrator,$f as defineModel,ry as defineModelFactory,Pf as defineRelations,vf as defineView,Xv as generateOpenApiModel,eB as generateOpenApiModelSchema,Ep as generateOpenApiModelWithMetadata,_ as logger,Iy as prop,za as redis,j as withPerformance};//# sourceMappingURL=index.js.map
|
|
331
331
|
//# sourceMappingURL=index.js.map
|