hysteria-orm 12.2.0 → 12.2.2

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {PassThrough,Readable}from'stream';import {Command}from'commander';import ae,{promises}from'fs';import yt from'path';import qu from'fs/promises';import {format}from'sql-formatter';import {highlight}from'sql-highlight';import {createRequire}from'module';import {pathToFileURL}from'url';import Pe,{privateDecrypt,publicEncrypt}from'crypto';import {AsyncLocalStorage}from'async_hooks';import {execSync}from'child_process';import Ig from'readline';var du=Object.defineProperty;var cu=i=>{throw TypeError(i)};var ve=(i,t)=>()=>(i&&(t=i(i=0)),t);var mu=(i,t)=>{for(var e in t)du(i,e,{get:t[e],enumerable:true});};var pu=(i,t,e,r)=>{for(var n=void 0,o=i.length-1,s;o>=0;o--)(s=i[o])&&(n=(s(t,e,n))||n);return n&&du(t,e,n),n};var Ey=(i,t,e)=>t.has(i)||cu("Cannot "+e);var fu=(i,t,e)=>t.has(i)?cu("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e);var yu=(i,t,e)=>(Ey(i,t,"access private method"),e);var L,ue=ve(()=>{L=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};});var Xf,ge,dg,ey,Dt=ve(()=>{ue();Xf=[],ge=i=>{Xf.push(i);},dg=async(i,t,e,r)=>{if(!Array.isArray(t?.dialects))throw new Error(`driver must be a registered driver name or a DriverAdapterFactory with a "dialects" array (got ${typeof t}).`);if(!t.dialects.includes(i))throw new Error(`driver "${t.name}" does not support dialect "${i}" (declares: ${t.dialects.join(", ")}).`);return t.create({dialect:i,jsEnvironment:e,input:r})},ey=async(i,t,e,r)=>{if(e&&typeof e!="string")return dg(i,e,t,r);let n=Xf.filter(l=>l.dialects.includes(i)),o=(l,u)=>(l.environments??["node"]).includes(u),s=(l,u)=>(e?l.name===e:true)&&o(l,u),a=n.find(l=>s(l,t));if(a)return a.create({dialect:i,jsEnvironment:t,input:r});if(t==="bun"){let l=n.find(u=>s(u,"node"));if(l)return l.create({dialect:i,jsEnvironment:t,input:r})}throw new L(e??i)};});var At,hg,ry,Xt=ve(()=>{At=async(i,t={},e)=>{let r=new PassThrough({objectMode:t.objectMode??true,highWaterMark:t.highWaterMark});try{for(let n of i)e.onData?await e.onData(r,n):r.write(n);r.end();}catch(n){r.destroy(n);}return r},hg=i=>{if(i.writableNeedDrain)return new Promise(t=>i.once("drain",()=>t()))},ry=async(i,t={},e)=>{let r=new PassThrough({objectMode:t.objectMode??true,highWaterMark:t.highWaterMark});try{for(let n of i)e.onData?await e.onData(r,n):r.write(n),await hg(r);r.end();}catch(n){r.destroy(n);}return r};});var ny,_n,oy=ve(()=>{Xt();ny=i=>{if(!i||typeof i!="object")return i;let t=i,e=t.errno,r=typeof e=="string"&&/^[0-9A-Z]{5}$/.test(e),n=typeof t.code=="string"&&t.code.startsWith("ERR_");return !r||!n||(t.cause===void 0&&(t.cause=i),t.code=e),i},_n=class{constructor(t,e,r){this.jsEnvironment="bun";this.dialect=t;let n={hostname:e.host,port:e.port,username:e.username,password:e.password,database:e.database,...e.driverOptions};(t==="mysql"||t==="mariadb")&&(n.adapter="mysql",n.allowPublicKeyRetrieval=true),this.sql=new r(n),this.pool=this.sql;}createPool(){}async closePool(){this.sql.close();}async reserveConnection(){return this.sql.reserve()}releaseConnection(t){t?.release();}async beginTransaction(t,e){(this.dialect==="mysql"||this.dialect==="mariadb")&&e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`),await e.rawQuery(this.dialect==="mysql"||this.dialect==="mariadb"?"START TRANSACTION":"BEGIN TRANSACTION"),(this.dialect==="postgres"||this.dialect==="cockroachdb")&&e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`);}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.sql,o;try{o=await n.unsafe(t,e);}catch(a){throw ny(a)}if(this.dialect==="mysql"||this.dialect==="mariadb"){let a=/^\s*(select|show|desc(ribe)?|explain)\b/i.test(t);if(Array.isArray(o)&&(a||o.length>0))return [o,void 0];let l=o;return [{affectedRows:Number(l.affectedRows),insertId:Number(l.lastInsertRowid)},void 0]}let s=o;return Array.isArray(o)&&!((s.command==="INSERT"||s.command==="UPDATE"||s.command==="DELETE")&&o.length===0)?{rows:o,rowCount:o.length}:{rows:[],rowCount:s.count??s.affectedRows??0}}extract(t,e){if(e==="raw")return t;if(this.dialect==="mysql"||this.dialect==="mariadb"){let n=t;return e==="affectedRows"?n[0]?.affectedRows??0:n[0]}let r=t;return e==="affectedRows"?r.rowCount:r.rows}async stream(t,e,r,n){let o=r.connection??this.sql,s;try{s=await o.unsafe(t,e);}catch(l){throw ny(l)}let a=Array.isArray(s)?s:[];return At(a,r,n)}};});var Mn,sy=ve(()=>{Xt();Mn=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="bun";this.db=new r(String(e.database??":memory:"),e.driverOptions),this.pool=this.db;}createPool(){}async closePool(){this.db.close();}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.db,o=r.sqlLiteOptions??{},s=o.mode||"fetch";return ["begin","begin transaction","commit","rollback"].includes(t.trim().toLowerCase())?n.query(t).run(...e).changes:s==="fetch"?n.query(t).all(...e):o?.typeofModel?s==="insertOne"||s==="insertMany"?n.query(`${t} returning *`).all(...e):n.query(t).run(...e).changes:n.query(t).run(...e).changes}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.db;return ry(o.query(t).iterate(...e),r,n)}};});var iy={};mu(iy,{registerBunDrivers:()=>gg});var gg,ay=ve(()=>{Dt();oy();sy();gg=async()=>{let{SQL:i}=await import('bun'),{Database:t}=await import('bun:sqlite');ge({name:"bun-sql",dialects:["postgres","cockroachdb","mysql","mariadb"],environments:["bun"],create:async({dialect:e,input:r})=>new _n(e,r,i)}),ge({name:"bun-sqlite",dialects:["sqlite"],environments:["bun"],create:async({dialect:e,input:r})=>new Mn(e,r,t)});};});var bg,xn,Yl,Zl=ve(()=>{Xt();bg=async i=>(await(await import('@sqlite.org/sqlite-wasm')).default(i)).oo1,xn=class{constructor(t,e,r=bg,n){this.dialect="sqlite";this.jsEnvironment="web";this.filename=String(e.database??":memory:"),this.loader=r,this.initConfig=n;}async createPool(){let t=await this.loader(this.initConfig),{filename:e}=this;this.db=e.startsWith(":memory:")||e===""?new t.DB(e):t.OpfsDb?new t.OpfsDb(e,"c"):new t.DB(e,"c"),this.pool=this.db;}async closePool(){this.db?.close();}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.requireDb(),o=r.sqlLiteOptions??{},s=o.mode||"fetch",a=u=>(n.exec(u,{bind:e}),n.changes());return Yl(t)?a(t):s==="fetch"?n.selectObjects(t,e):o?.typeofModel&&(s==="insertOne"||s==="insertMany")?n.selectObjects(`${t} returning *`,e):a(t)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.requireDb();return At(o.selectObjects(t,e),r,n)}requireDb(){if(!this.db)throw new Error("sqlite-wasm: pool not created, await createPool() before querying");return this.db}},Yl=i=>["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase());});var Xl,On,ly=ve(()=>{Xt();Zl();Xl=i=>Array.isArray(i)?i:i?._array??[],On=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="react-native";this.filename=String(e.database??":memory:"),this.engine=r;}createPool(){this.db=this.engine.open({name:this.filename}),this.pool=this.db;}async closePool(){this.db?.close();}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.requireDb(),o=r.sqlLiteOptions??{},s=o.mode||"fetch",a=async u=>(await n.execute(u,e)).rowsAffected??0;if(Yl(t))return a(t);if(s==="fetch"){let u=await n.execute(t,e);return Xl(u.rows)}if(!o?.typeofModel)return a(t);if(s==="insertOne"||s==="insertMany"){let u=await n.execute(`${t} returning *`,e);return Xl(u.rows)}return a(t)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let s=await(r.connection??this.requireDb()).execute(t,e);return At(Xl(s.rows),r,n)}requireDb(){if(!this.db)throw new Error("sqlite-rn: pool not created, await createPool() before querying");return this.db}};});var eu={};mu(eu,{registerReactNativeDrivers:()=>wg,registerWebDrivers:()=>Tg});var uy,dy,Tg,cy,wg,tu=ve(()=>{Dt();ly();Zl();uy=false,Tg=i=>{uy||(uy=true,dy=i,ge({name:"sqlite-wasm",dialects:["sqlite"],environments:["web"],create:({dialect:t,input:e})=>new xn(t,e,void 0,dy)}));},cy=false,wg=async()=>{if(cy)return;cy=true;let i=await import('@op-engineering/op-sqlite');ge({name:"sqlite-rn",dialects:["sqlite"],environments:["react-native"],create:({dialect:t,input:e})=>new On(t,e,i)});};});var vt=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";default:return "sql"}},kn=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)},it=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,kn(t[r]));for(let r=0;r<t.length;r++){let n=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(n,kn(t[r]));}for(let r=0;r<t.length;r++){let n=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(n,kn(t[r]));}return e},at=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:false:false,lt=(i,t)=>{let e=i.getDbType(),r;try{r=format(t,{...i.inputDetails.queryFormatOptions,language:vt(e)});}catch{try{r=format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var gu={info:0,warn:1,error:2};function lr(i){return i?i===true?{level:"info",logQueries:true}:{level:i.level??"info",logQueries:i.logQueries??true,customLogger:i.customLogger}:null}function Ky(i,t="info"){let e=lr(i);if(!e)return false;let r=e.level??"info";return gu[t]>=gu[r]}function Qy(i){let t=lr(i);return t?t.logQueries??true:false}var ke={info:"32",warn:"33",error:"31",query:"35",dim:"2",cyan:"36"},Ly=typeof process<"u"&&!!process.stdout?.isTTY&&!process.env.NO_COLOR,ut=(i,t)=>Ly?`\x1B[${i}m${t}\x1B[0m`:t;function Su(){let i=new Date,t=r=>r.toString().padStart(2,"0"),e=i.getMilliseconds().toString().padStart(3,"0");return `${t(i.getHours())}:${t(i.getMinutes())}:${t(i.getSeconds())}.${e}`}function Kn(i,t){let e=ut(ke.dim,`[${Su()}]`),r=ut(ke[i],i.toUpperCase().padEnd(5));return `${e} ${r} ${t}`}var Wy=60,jy=10,bu=400;function ar(i,t=Wy){return i.length<=t?i:`${i.slice(0,t)}\u2026`}function Fy(i){if(i==null)return "null";if(typeof i=="string")return `'${ar(i)}'`;if(typeof i=="number"||typeof i=="bigint")return String(i);if(typeof i=="boolean")return i?"true":"false";if(i instanceof Date)return `'${ar(i.toISOString())}'`;if(typeof i=="object"){let t;try{t=JSON.stringify(i);}catch{t=String(i);}return `'${ar(t)}'`}return ar(String(i))}function Uy(i){if(!i||i.length===0)return "[]";let t=i.slice(0,jy).map(Fy),e=i.length-t.length;e>0&&t.push(`\u2026 (${e} more)`);let r=`[${t.join(", ")}]`;return r.length>bu&&(r=`${r.slice(0,bu)}\u2026`),r}var Tu=(i,t)=>{let e=" ".repeat(t);return i.split(`
2
+ import {PassThrough,Readable}from'stream';import {Command}from'commander';import ae,{promises}from'fs';import yt from'path';import qu from'fs/promises';import {format}from'sql-formatter';import {highlight}from'sql-highlight';import {createRequire}from'module';import {pathToFileURL}from'url';import Pe,{privateDecrypt,publicEncrypt}from'crypto';import {AsyncLocalStorage}from'async_hooks';import {execSync}from'child_process';import Bg from'readline';var du=Object.defineProperty;var cu=i=>{throw TypeError(i)};var ve=(i,t)=>()=>(i&&(t=i(i=0)),t);var mu=(i,t)=>{for(var e in t)du(i,e,{get:t[e],enumerable:true});};var pu=(i,t,e,r)=>{for(var n=void 0,o=i.length-1,s;o>=0;o--)(s=i[o])&&(n=(s(t,e,n))||n);return n&&du(t,e,n),n};var Ey=(i,t,e)=>t.has(i)||cu("Cannot "+e);var fu=(i,t,e)=>t.has(i)?cu("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e);var yu=(i,t,e)=>(Ey(i,t,"access private method"),e);var L,ue=ve(()=>{L=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};});var Xf,ge,pg,ey,Dt=ve(()=>{ue();Xf=[],ge=i=>{Xf.push(i);},pg=async(i,t,e,r)=>{if(!Array.isArray(t?.dialects))throw new Error(`driver must be a registered driver name or a DriverAdapterFactory with a "dialects" array (got ${typeof t}).`);if(!t.dialects.includes(i))throw new Error(`driver "${t.name}" does not support dialect "${i}" (declares: ${t.dialects.join(", ")}).`);return t.create({dialect:i,jsEnvironment:e,input:r})},ey=async(i,t,e,r)=>{if(e&&typeof e!="string")return pg(i,e,t,r);let n=Xf.filter(l=>l.dialects.includes(i)),o=(l,u)=>(l.environments??["node"]).includes(u),s=(l,u)=>(e?l.name===e:true)&&o(l,u),a=n.find(l=>s(l,t));if(a)return a.create({dialect:i,jsEnvironment:t,input:r});if(t==="bun"){let l=n.find(u=>s(u,"node"));if(l)return l.create({dialect:i,jsEnvironment:t,input:r})}throw new L(e??i)};});var At,Tg,ry,Xt=ve(()=>{At=async(i,t={},e)=>{let r=new PassThrough({objectMode:t.objectMode??true,highWaterMark:t.highWaterMark});try{for(let n of i)e.onData?await e.onData(r,n):r.write(n);r.end();}catch(n){r.destroy(n);}return r},Tg=i=>{if(i.writableNeedDrain)return new Promise(t=>i.once("drain",()=>t()))},ry=async(i,t={},e)=>{let r=new PassThrough({objectMode:t.objectMode??true,highWaterMark:t.highWaterMark});try{for(let n of i)e.onData?await e.onData(r,n):r.write(n),await Tg(r);r.end();}catch(n){r.destroy(n);}return r};});var ny,_n,oy=ve(()=>{Xt();ny=i=>{if(!i||typeof i!="object")return i;let t=i,e=t.errno,r=typeof e=="string"&&/^[0-9A-Z]{5}$/.test(e),n=typeof t.code=="string"&&t.code.startsWith("ERR_");return !r||!n||(t.cause===void 0&&(t.cause=i),t.code=e),i},_n=class{constructor(t,e,r){this.jsEnvironment="bun";this.dialect=t;let n={hostname:e.host,port:e.port,username:e.username,password:e.password,database:e.database,...e.driverOptions};(t==="mysql"||t==="mariadb")&&(n.adapter="mysql",n.allowPublicKeyRetrieval=true),this.sql=new r(n),this.pool=this.sql;}createPool(){}async closePool(){this.sql.close();}async reserveConnection(){return this.sql.reserve()}releaseConnection(t){t?.release();}async beginTransaction(t,e){(this.dialect==="mysql"||this.dialect==="mariadb")&&e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`),await e.rawQuery(this.dialect==="mysql"||this.dialect==="mariadb"?"START TRANSACTION":"BEGIN TRANSACTION"),(this.dialect==="postgres"||this.dialect==="cockroachdb")&&e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`);}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.sql,o;try{o=await n.unsafe(t,e);}catch(a){throw ny(a)}if(this.dialect==="mysql"||this.dialect==="mariadb"){let a=/^\s*(select|show|desc(ribe)?|explain)\b/i.test(t);if(Array.isArray(o)&&(a||o.length>0))return [o,void 0];let l=o;return [{affectedRows:Number(l.affectedRows),insertId:Number(l.lastInsertRowid)},void 0]}let s=o;return Array.isArray(o)&&!((s.command==="INSERT"||s.command==="UPDATE"||s.command==="DELETE")&&o.length===0)?{rows:o,rowCount:o.length}:{rows:[],rowCount:s.count??s.affectedRows??0}}extract(t,e){if(e==="raw")return t;if(this.dialect==="mysql"||this.dialect==="mariadb"){let n=t;return e==="affectedRows"?n[0]?.affectedRows??0:n[0]}let r=t;return e==="affectedRows"?r.rowCount:r.rows}async stream(t,e,r,n){let o=r.connection??this.sql,s;try{s=await o.unsafe(t,e);}catch(l){throw ny(l)}let a=Array.isArray(s)?s:[];return At(a,r,n)}};});var Mn,sy=ve(()=>{Xt();Mn=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="bun";this.db=new r(String(e.database??":memory:"),e.driverOptions),this.pool=this.db;}createPool(){}async closePool(){this.db.close();}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.db,o=r.sqlLiteOptions??{},s=o.mode||"fetch";return ["begin","begin transaction","commit","rollback"].includes(t.trim().toLowerCase())?n.query(t).run(...e).changes:s==="fetch"?n.query(t).all(...e):o?.typeofModel?s==="insertOne"||s==="insertMany"?n.query(`${t} returning *`).all(...e):n.query(t).run(...e).changes:n.query(t).run(...e).changes}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.db;return ry(o.query(t).iterate(...e),r,n)}};});var iy={};mu(iy,{registerBunDrivers:()=>wg});var wg,ay=ve(()=>{Dt();oy();sy();wg=async()=>{let{SQL:i}=await import('bun'),{Database:t}=await import('bun:sqlite');ge({name:"bun-sql",dialects:["postgres","cockroachdb","mysql","mariadb"],environments:["bun"],create:async({dialect:e,input:r})=>new _n(e,r,i)}),ge({name:"bun-sqlite",dialects:["sqlite"],environments:["bun"],create:async({dialect:e,input:r})=>new Mn(e,r,t)});};});var Sg,xn,Yl,Zl=ve(()=>{Xt();Sg=async i=>(await(await import('@sqlite.org/sqlite-wasm')).default(i)).oo1,xn=class{constructor(t,e,r=Sg,n){this.dialect="sqlite";this.jsEnvironment="web";this.filename=String(e.database??":memory:"),this.loader=r,this.initConfig=n;}async createPool(){let t=await this.loader(this.initConfig),{filename:e}=this;this.db=e.startsWith(":memory:")||e===""?new t.DB(e):t.OpfsDb?new t.OpfsDb(e,"c"):new t.DB(e,"c"),this.pool=this.db;}async closePool(){this.db?.close();}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.requireDb(),o=r.sqlLiteOptions??{},s=o.mode||"fetch",a=u=>(n.exec(u,{bind:e}),n.changes());return Yl(t)?a(t):s==="fetch"?n.selectObjects(t,e):o?.typeofModel&&(s==="insertOne"||s==="insertMany")?n.selectObjects(`${t} returning *`,e):a(t)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.requireDb();return At(o.selectObjects(t,e),r,n)}requireDb(){if(!this.db)throw new Error("sqlite-wasm: pool not created, await createPool() before querying");return this.db}},Yl=i=>["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase());});var Xl,On,ly=ve(()=>{Xt();Zl();Xl=i=>Array.isArray(i)?i:i?._array??[],On=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="react-native";this.filename=String(e.database??":memory:"),this.engine=r;}createPool(){this.db=this.engine.open({name:this.filename}),this.pool=this.db;}async closePool(){this.db?.close();}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=r.connection??this.requireDb(),o=r.sqlLiteOptions??{},s=o.mode||"fetch",a=async u=>(await n.execute(u,e)).rowsAffected??0;if(Yl(t))return a(t);if(s==="fetch"){let u=await n.execute(t,e);return Xl(u.rows)}if(!o?.typeofModel)return a(t);if(s==="insertOne"||s==="insertMany"){let u=await n.execute(`${t} returning *`,e);return Xl(u.rows)}return a(t)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let s=await(r.connection??this.requireDb()).execute(t,e);return At(Xl(s.rows),r,n)}requireDb(){if(!this.db)throw new Error("sqlite-rn: pool not created, await createPool() before querying");return this.db}};});var eu={};mu(eu,{registerReactNativeDrivers:()=>qg,registerWebDrivers:()=>Ng});var uy,dy,Ng,cy,qg,tu=ve(()=>{Dt();ly();Zl();uy=false,Ng=i=>{uy||(uy=true,dy=i,ge({name:"sqlite-wasm",dialects:["sqlite"],environments:["web"],create:({dialect:t,input:e})=>new xn(t,e,void 0,dy)}));},cy=false,qg=async()=>{if(cy)return;cy=true;let i=await import('@op-engineering/op-sqlite');ge({name:"sqlite-rn",dialects:["sqlite"],environments:["react-native"],create:({dialect:t,input:e})=>new On(t,e,i)});};});var vt=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";default:return "sql"}},kn=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)},it=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,kn(t[r]));for(let r=0;r<t.length;r++){let n=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(n,kn(t[r]));}for(let r=0;r<t.length;r++){let n=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(n,kn(t[r]));}return e},at=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:false:false,lt=(i,t)=>{let e=i.getDbType(),r;try{r=format(t,{...i.inputDetails.queryFormatOptions,language:vt(e)});}catch{try{r=format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var gu={info:0,warn:1,error:2};function lr(i){return i?i===true?{level:"info",logQueries:true}:{level:i.level??"info",logQueries:i.logQueries??true,customLogger:i.customLogger}:null}function Ky(i,t="info"){let e=lr(i);if(!e)return false;let r=e.level??"info";return gu[t]>=gu[r]}function Qy(i){let t=lr(i);return t?t.logQueries??true:false}var ke={info:"32",warn:"33",error:"31",query:"35",dim:"2",cyan:"36"},Ly=typeof process<"u"&&!!process.stdout?.isTTY&&!process.env.NO_COLOR,ut=(i,t)=>Ly?`\x1B[${i}m${t}\x1B[0m`:t;function Su(){let i=new Date,t=r=>r.toString().padStart(2,"0"),e=i.getMilliseconds().toString().padStart(3,"0");return `${t(i.getHours())}:${t(i.getMinutes())}:${t(i.getSeconds())}.${e}`}function Kn(i,t){let e=ut(ke.dim,`[${Su()}]`),r=ut(ke[i],i.toUpperCase().padEnd(5));return `${e} ${r} ${t}`}var Wy=60,jy=10,bu=400;function ar(i,t=Wy){return i.length<=t?i:`${i.slice(0,t)}\u2026`}function Fy(i){if(i==null)return "null";if(typeof i=="string")return `'${ar(i)}'`;if(typeof i=="number"||typeof i=="bigint")return String(i);if(typeof i=="boolean")return i?"true":"false";if(i instanceof Date)return `'${ar(i.toISOString())}'`;if(typeof i=="object"){let t;try{t=JSON.stringify(i);}catch{t=String(i);}return `'${ar(t)}'`}return ar(String(i))}function Uy(i){if(!i||i.length===0)return "[]";let t=i.slice(0,jy).map(Fy),e=i.length-t.length;e>0&&t.push(`\u2026 (${e} more)`);let r=`[${t.join(", ")}]`;return r.length>bu&&(r=`${r.slice(0,bu)}\u2026`),r}var Tu=(i,t)=>{let e=" ".repeat(t);return i.split(`
3
3
  `).map(r=>`${e}${r}`).join(`
4
4
  `)};function Vy(i){let t=i<10?ke.info:i<100?ke.warn:ke.error;return ut(t,`(${i}ms)`)}function Jy(i,t,e){let r=ut(ke.dim,`[${Su()}]`),n=ut(ke.query,"QUERY"),s=[e===void 0?`${r} ${n}`:`${r} ${n} ${Vy(e)}`,Tu(i,2)];return t&&t.length>0&&s.push(Tu(`parameters: ${ut(ke.cyan,Uy(t))}`,4)),s.join(`
5
5
  `)}var wu={info(i){console.log(Kn("info",i));},error(i){console.error(Kn("error",i));},warn(i){console.warn(Kn("warn",i));}},dt=class{static setCustomLogger(t){this.loggerInstance=t;}static info(t){this.loggerInstance.info(t);}static error(t){this.loggerInstance.error(t instanceof Error?String(t):t);}static warn(t){this.loggerInstance.warn(t);}static query(t){if(this.loggerInstance===wu){console.log(t);return}this.loggerInstance.info(t);}};dt.loggerInstance=wu;function ct(i,t,e,r,n,o){if(!Qy(t))return;let s=i;if(r||n)try{s=format(i,{...r,language:r?.language??(n?vt(n):void 0)});}catch{s=i;}let a=highlight(s,{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"}});dt.query(Jy(a,e,o));}function Nu(i,t,e=false){Ky(e,t)&&dt.loggerInstance[t](i);}var g=dt;var Qn=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return r[0].map(o=>o[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.rows.map(o=>o.table_name);case "mssql":return r.recordset.map(o=>o.TABLE_NAME);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
@@ -118,7 +118,7 @@ CREATE TABLE [migrations] (
118
118
  FROM sys.foreign_keys;
119
119
  `)).recordset;for(let p of m)await i.rawQuery(`ALTER TABLE [${p.table_name}] DROP CONSTRAINT [${p.constraint_name}];`);}await i.rawQuery(d),(r==="mysql"||r==="mariadb")&&await i.rawQuery("SET FOREIGN_KEY_CHECKS = 1;"),s&&await o?.commit(),g.info("All tables dropped successfully");}catch(a){throw s&&await o?.rollback(),g.error(a),a}finally{t&&await i.disconnect();}}function ur(i){if(i&&i!=="auto")return i;if(typeof process<"u"&&process.versions?.bun)return "bun";if(globalThis.navigator?.product==="ReactNative"||"HermesInternal"in globalThis)return "react-native";let e=typeof globalThis.self<"u";return typeof window<"u"||typeof document<"u"||e?"web":"node"}var Hy=i=>{i[6]=i[6]&15|64,i[8]=i[8]&63|128;let t=Qe(i);return [t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")},Cu=i=>{let t=globalThis.crypto;if(!t||typeof t.getRandomValues!="function")throw new mt("crypto.getRandomValues \u2014 browsers require a secure context (HTTPS); React Native requires react-native-get-random-values or expo-crypto");return t.getRandomValues(i)},Wn=class{unsupported(t){throw new mt(`fs.${t}`)}exists(){return this.unsupported("exists")}readFileSync(){return this.unsupported("readFileSync")}readFile(){return this.unsupported("readFile")}readdir(){return this.unsupported("readdir")}mkdir(){return this.unsupported("mkdir")}writeFile(){return this.unsupported("writeFile")}rm(){return this.unsupported("rm")}},jn=class{join(...t){return t.filter(Boolean).join("/").replace(/\/+/g,"/")}dirname(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}basename(t,e){let r=t.slice(t.lastIndexOf("/")+1);return e&&r.endsWith(e)?r.slice(0,-e.length):r}resolve(...t){let e=t.filter(Boolean).join("/").replace(/\/+/g,"/");return e.startsWith("/")?e:`/${e}`}},Ke=class{constructor(){this.name="web";this.crypto={randomUUID:()=>{let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():Hy(Cu(new Uint8Array(16)))},randomBytes:t=>Cu(new Uint8Array(t))};this.timing={now:()=>globalThis.performance.now()};this.fs=new Wn;this.path=new jn;}readEnv(t){}};var pt=class extends Ke{constructor(){super(...arguments);this.name="node";this.fs={exists:e=>ae.existsSync(e),readFileSync:e=>ae.existsSync(e)?new Uint8Array(ae.readFileSync(e)):null,readFile:async e=>promises.readFile(e,"utf8"),readdir:e=>promises.readdir(e),mkdir:async(e,r)=>{await promises.mkdir(e,{recursive:r?.recursive});},writeFile:async(e,r)=>{await promises.writeFile(e,r);},rm:async(e,r)=>{await promises.rm(e,{recursive:r?.recursive,force:r?.force});}};this.path=yt;}readEnv(e){return typeof process>"u"?void 0:process.env[e]}};var Un=()=>import('bun'),dr=class extends pt{constructor(){super();this.name="bun";let e=this.fs;this.fs={...e,readFile:async r=>(await Un()).file(r).text(),readdir:async r=>{let n=await Un(),o=[];for await(let s of new n.Glob("*").scan({cwd:r}))o.push(s);return o},writeFile:async(r,n)=>{await(await Un()).write(r,n);}};}};var cr=class extends Ke{constructor(){super(...arguments);this.name="react-native";}};var mt=class extends Error{constructor(t){super(`Platform does not support: ${t}`),this.name="PlatformUnsupportedError";}},Qe=i=>{let t="";for(let e of i)t+=e.toString(16).padStart(2,"0");return t},Ru=new Map,Gy=i=>{switch(i){case "bun":return new dr;case "node":return new pt;case "react-native":return new cr;default:return new Ke}};function ie(i){let t=ur(i),e=Ru.get(t);return e||(e=Gy(t),Ru.set(t,e)),e}var ee=ie(),I={DB_TYPE:ee.readEnv("DB_TYPE"),DB_HOST:ee.readEnv("DB_HOST"),DB_PORT:ee.readEnv("DB_PORT"),DB_USER:ee.readEnv("DB_USER"),DB_PASSWORD:ee.readEnv("DB_PASSWORD"),DB_DATABASE:ee.readEnv("DB_DATABASE"),DB_LOGS:ee.readEnv("DB_LOGS")==="true",MIGRATION_PATH:ee.readEnv("MIGRATION_PATH")||"database/migrations",REDIS_HOST:ee.readEnv("REDIS_HOST"),REDIS_PORT:ee.readEnv("REDIS_PORT"),REDIS_USERNAME:ee.readEnv("REDIS_USERNAME"),REDIS_PASSWORD:ee.readEnv("REDIS_PASSWORD"),REDIS_DATABASE:ee.readEnv("REDIS_DATABASE"),MONGO_URL:ee.readEnv("MONGO_URL"),MONGO_LOGS:ee.readEnv("MONGO_LOGS")==="true",MSSQL_TRUST_SERVER_CERTIFICATE:ee.readEnv("MSSQL_TRUST_SERVER_CERTIFICATE")==="true"||false},Yy=()=>{try{if(!ee.fs.exists(".env"))return I;let i=ee.fs.readFileSync(".env");if(!i)return I;new TextDecoder().decode(i).split(`
120
120
  `).forEach(r=>{let[n,o]=r.split("="),s=n.trim(),a=o.trim();switch(s){case "DB_TYPE":I.DB_TYPE||(I.DB_TYPE=a);break;case "DB_HOST":I.DB_HOST||(I.DB_HOST=a);break;case "DB_PORT":I.DB_PORT||(I.DB_PORT=a);break;case "DB_USER":I.DB_USER||(I.DB_USER=a);break;case "DB_PASSWORD":I.DB_PASSWORD||(I.DB_PASSWORD=a);break;case "DB_DATABASE":I.DB_DATABASE||(I.DB_DATABASE=a);break;case "MIGRATION_PATH":I.MIGRATION_PATH||(I.MIGRATION_PATH=a||"database/migrations");break;case "REDIS_HOST":I.REDIS_HOST||(I.REDIS_HOST=a);break;case "REDIS_PORT":I.REDIS_PORT||(I.REDIS_PORT=a);break;case "REDIS_USERNAME":I.REDIS_USERNAME||(I.REDIS_USERNAME=a);break;case "REDIS_PASSWORD":I.REDIS_PASSWORD||(I.REDIS_PASSWORD=a);break;case "REDIS_DATABASE":I.REDIS_DATABASE||(I.REDIS_DATABASE=a);break;case "MONGO_URL":I.MONGO_URL||(I.MONGO_URL=a);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":I.MSSQL_TRUST_SERVER_CERTIFICATE||(I.MSSQL_TRUST_SERVER_CERTIFICATE=a==="true");break}});}catch{}finally{return I}},E=Yy();var Zy=()=>{let i=E.MIGRATION_PATH,t=yt.resolve(process.cwd(),i);return ae.existsSync(t)||ae.mkdirSync(t,{recursive:true}),t},Mu=(i,t=false,e="basic",r="table")=>{let n=Zy(),o=new Date().getTime(),s=t?`${o}_${i}.js`:`${o}_${i}.ts`,a=yt.join(n,s),l;switch(e){case "alter":l=oe.alterMigrationTemplate(t,r);break;case "create":l=oe.createMigrationTemplate(t,r);break;default:l=oe.basicMigrationTemplate(t);break}ae.writeFileSync(a,l),g.info(`Migration created successfully at '${a}'.`),process.exit(0);};var S=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}},Pt=class extends S{constructor(t){super("ValidationError","VALIDATION_ERROR"),this.errors=t;}};async function th(i){try{return import(pathToFileURL(i).href)}catch{let e=createRequire(import.meta.url)(i);return {default:e.default||e,...e}}}async function rh(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 ae.promises.unlink(r).catch(()=>{});}}async function ft(i,t){let e=yt.isAbsolute(i)?i:yt.resolve(process.cwd(),i);return e.endsWith(".ts")?rh(e):th(e)}var sh=async(i,t)=>{if(i.endsWith(".ts"))return ft(i);try{return import(pathToFileURL(i).href)}catch{let n=createRequire(import.meta.url);try{let o=n(i);return {default:o.default||o,...o}}catch{throw new S(`MigrationUtils::importMigrationFile Failed to import migration file: ${i}. Both ESM and CommonJS imports failed.`,"MIGRATION_MODULE_NOT_FOUND")}}};async function pr(i,t){switch(i){case "mariadb":case "mysql":return await t.rawQuery(oe.migrationTableTemplateMysql()),(await t.rawQuery(oe.selectAllFromMigrationsTemplate()))[0];case "postgres":case "cockroachdb":return await t.rawQuery(oe.migrationTableTemplatePg()),(await t.rawQuery(oe.selectAllFromMigrationsTemplate())).rows;case "sqlite":return await t.rawQuery(oe.migrationTableTemplateSQLite()),await t.rawQuery(oe.selectAllFromMigrationsTemplate());case "mssql":return await t.rawQuery(oe.migrationTableTemplateMssql()),(await t.rawQuery(oe.selectAllFromMigrationsTemplate())).recordset;default:throw new S("MigrationUtils::getMigrationTable Unsupported database type","DEVELOPMENT_ERROR")}}async function fr(i,t,e){let r=ah(t),n=[];for(let{name:o,fullPath:s}of r){let a=await ih(s),l=new a(i||E.DB_TYPE);l.migrationName=o,n.push(l);}return n}async function ih(i,t){let e=await sh(i);if(!e.default)throw new S("MigrationUtils::loadMigrationModule Migration module does not have a default export","MIGRATION_MODULE_NOT_FOUND");return e.default}function ah(i){let t=process.cwd(),e=i||E.MIGRATION_PATH||"database/migrations",r=/[*?{}\[\]]/.test(e);if(!r){let s=yt.isAbsolute(e)?e:yt.resolve(t,e);if(!ae.existsSync(s))return ae.mkdirSync(s,{recursive:true}),[]}let n=r?e:yt.join(e,"**/*.{ts,js}"),o=yt.isAbsolute(n)?n:yt.resolve(t,n);try{return ae.globSync(o).filter(a=>ae.statSync(a).isFile()).sort().map(a=>({name:yt.basename(a),fullPath:a}))}catch{return []}}async function Et(i,t,e,r,n){let o=i.getDbType(),s=n&&o!=="mssql",a=null;g.info("Running migrations for database type: "+o);try{let l=await pr(o,i),d=(await fr(o,e,r)).filter(m=>!l.map(p=>p.name).includes(m.migrationName));if(!d.length){g.info("No pending migrations.");return}if(t){let m=d.findIndex(f=>f.migrationName===t);if(m===-1){console.error(`Migration ${t} not found.`);return}let p=d.slice(0,m+1);s&&(a=await i.transaction(),i=a.sql),await new Le(i).upMigrations(p),s&&await a?.commit(),g.info("Migrations ran successfully");return}s&&(a=await i.transaction(),i=a.sql),await new Le(i).upMigrations(d),s&&await a?.commit();}catch(l){throw s&&await a?.rollback(),l}g.info("Migrations ran successfully");}ue();var yr={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 Au=null;function Ze(i,t){return t.getModelManager(i)}function Du(i,t,e){if(!t||typeof t!="object")return;let r=t;if(!r.filters)return;let n=e.getColumns();for(let[o,s]of Object.entries(r.filters)){let a=s.value;if(a==null||a==="")continue;let l=n.find(c=>c.columnName===o||c.databaseName===o);if(!l)continue;let u=typeof l.type=="string"?l.type:"string",d=yr[u]||"string";if(d==="string"||d==="textarea"){i.whereLike(o,`%${a}%`);continue}if(d==="boolean"){i.where(o,a==="true"||a===true);continue}if(d==="date"||d==="datetime"){if(typeof a=="object"&&a!==null){let c=a;c.from&&i.where(o,">=",c.from),c.to&&i.where(o,"<=",c.to);continue}i.where(o,a);continue}i.where(o,a);}}function Bt(i,t){let e={},r=t.getColumns();for(let n of r){let o=i[n.columnName];e[n.columnName]=o;}return e}async function lh(){let i=await import('adminjs').catch(()=>{throw new L("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(o){super(o),this._model=o,this._db=Au;}static isAdapterFor(o){if(typeof o!="function")return false;let s=o;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=yr[a]||"string";return new r({path:s.columnName,type:l,isId:s.isPrimary,isSortable:true})})}property(o){let a=this._model.getColumns().find(d=>d.columnName===o||d.databaseName===o);if(!a)return null;let l=typeof a.type=="string"?a.type:"string",u=yr[l]||"string";return new r({path:a.columnName,type:u,isId:a.isPrimary,isSortable:true})}async count(o){let a=Ze(this._model,this._db).query();return Du(a,o,this._model),a.getCount()}async find(o,s={}){let l=Ze(this._model,this._db).query();return Du(l,o,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(Bt(d,this._model),this))}async findOne(o){if(!this._model.primaryKey)return null;let l=await Ze(this._model,this._db).findOneByPrimaryKey(o);return l?new e(Bt(l,this._model),this):null}async findMany(o){let s=this._model.primaryKey;return s?(await Ze(this._model,this._db).query().whereIn(s,o).many()).map(u=>new e(Bt(u,this._model),this)):[]}async create(o){let a=await Ze(this._model,this._db).insert(o,{returning:["*"]});return Bt(a,this._model)}async update(o,s){if(!this._model.primaryKey)throw new Error("Model has no primary key");let l=Ze(this._model,this._db);if(!await l.findOneByPrimaryKey(o))throw new Error("Record not found");let d=await l.updateRecord(o,s,{returning:["*"]});return Bt(d,this._model)}async delete(o){if(!this._model.primaryKey)throw new Error("Model has no primary key");let a=Ze(this._model,this._db);await a.findOneByPrimaryKey(o)&&await a.deleteRecord(o);}}}async function uh(){let i=await import('adminjs').catch(()=>{throw new L("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function dh(){let i=await import('adminjs').catch(()=>{throw new L("adminjs")}),t=await lh(),e=await uh();i.default.registerAdapter({Database:e,Resource:t});}async function Jn(i,t){Au=i;let e=await import('adminjs').catch(()=>{throw new L("adminjs")});await dh();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 n=r.map(a=>{let l=t.resourceOptions?.[a.table]||{};return {resource:a,options:l}}),o={rootPath:t.rootPath||"/admin",resources:n};if(t.branding&&(o.branding=t.branding),t.locale?.language&&(o.locale=t.locale),t.assets&&(o.assets=t.assets),t.settings&&(o.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&&(o.pages=a);}return {admin:new e.default(o)}}async function $u(i,t){let{admin:e}=await Jn(i,t),r;try{r=await import('@adminjs/express');}catch{throw new L("@adminjs/express")}let n=r.buildRouter(e);return {admin:e,router:n}}var ht=new Map,We=new Map,hr=class{async get(t){return ht.get(t)}async set(t,e,r){let n=We.get(t);if(n&&(clearTimeout(n),We.delete(t)),ht.set(t,e),r){let o=setTimeout(()=>{ht.delete(t),We.delete(t);},r);We.set(t,o);}}async invalidate(t){let e=We.get(t);e&&(clearTimeout(e),We.delete(t)),ht.delete(t);}async invalidateAll(t){let e=ht.keys();for(let r of e)if(r.startsWith(t)){let n=We.get(r);n&&(clearTimeout(n),We.delete(r)),ht.delete(r);}}};var kt=class{constructor(t){switch(this.type=t?.type||E.DB_TYPE,this.type){case "mongo":this.handleMongoSource(t);break;case "cockroachdb":this.handleCockroachdbSource(t);break;case "postgres":this.handlePostgresSource(t);break;case "mariadb":case "mysql":this.handleMysqlSource(t);break;case "sqlite":this.handleSqliteSource(t);break;case "mssql":this.handleMssqlSource(t);break;default:throw new S(`Invalid database type: ${this.type}, please provide a valid database type in your input or in the .env file with the key DB_TYPE
121
- Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}let e=lr(this.logs);e?.customLogger&&g.setCustomLogger(e.customLogger);}handleCockroachdbSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||E.DB_DATABASE||":memory:",this.logs=t?.logs||E.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||E.MONGO_URL,this.logs=t?.logs||E.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=1433);}};var ch=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},mh=i=>i.openApi?.required??false,ph=i=>{let t=i.getColumns(),e={};for(let r of t)r.openApi?.excludeFromSwagger||(e[r.columnName]=ch(r));return e},fh=i=>{let t=i.getColumns(),e=[];for(let r of t)mh(r)&&e.push(r.columnName);return e||[]},yh=i=>{let t=ph(i),e=fh(i);return {type:"object",properties:t,required:e.length?e:[]}};var vu=i=>i.map(t=>({...yh(t),modelName:t.table,$id:t.table}));var Hn=(i,t)=>{let e=Pe.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var zn=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:n}=r.parse([e.column]),o=e.inlineConstraints;if(o&&o.length){let s=[];for(let a of o){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(n+=` ${s.join(" ")}`);}return {sql:`add ${n}`,bindings:[]}}},Iu=new zn;var Gn=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:n}=r.parse([e.constraint]);return {sql:`add ${n}`,bindings:[]}}},Pu=new Gn;var Yn=class{toSql(t){return {sql:`add primary key (${t.columns.map(n=>`[${n}]`).join(", ")})`,bindings:[]}}},Eu=new Yn;var Zn=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:n}=r.parse([e.newType]),[,...o]=n.trim().split(/\s+/),s=o.join(" ");e.newType.dataType==="uuid"&&(s=s.replace(/\s+default\s+.+$/i,"").trim());let 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:[]}}},Bu=new Zn;var N=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var gt=class extends N{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};function gr(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 br(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function Xn(i){if(typeof i!="string"||!i)return i;let t=br(i);return t.charAt(0).toUpperCase()+t.slice(1)}function H(i,t){return t==="preserve"?i:t==="snake"?gr(i):t==="camel"?br(i):t==="pascal"?Xn(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}function xe(i){return String(i).padStart(2,"0")}function gh(i,t){let e=i.getFullYear(),r=xe(i.getMonth()+1),n=xe(i.getDate()),o=xe(i.getHours()),s=xe(i.getMinutes()),a=xe(i.getSeconds());switch(t){case "ISO":return `${e}-${r}-${n} ${o}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${n}`;case "TIME_ONLY":return `${o}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}function ku(i,t){let e=i.getUTCFullYear(),r=xe(i.getUTCMonth()+1),n=xe(i.getUTCDate()),o=xe(i.getUTCHours()),s=xe(i.getUTCMinutes()),a=xe(i.getUTCSeconds());switch(t){case "ISO":return `${e}-${r}-${n} ${o}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${n}`;case "TIME_ONLY":return `${o}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}var de=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");return e==="LOCAL"?gh(i,t):ku(i,t)};var bt=(i=new Date)=>ku(i,"ISO");var bh=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},eo=i=>!i.expression&&(i.type==="date"||i.type==="datetime"||i.type==="timestamp"),y=class{constructor(t){this.model=t;this.modelColumnsMap=typeof t.getColumnsByName=="function"?t.getColumnsByName():new Map;let e=[],r=[];for(let n of this.modelColumnsMap.values())n.expression||((n.type==="ulid"||n.autoCreate==="js")&&e.push(n),n.autoUpdate&&r.push(n));this.jsInsertColumns=e,this.autoUpdateColumns=r;}formatStringColumn(t,e){if(e==="*")return "*";let r=this.resolveComputedExpression(e);if(r!==void 0)return `(${r})`;if(e.includes(".")){let[s,a]=e.split(".");if(a==="*")switch(t){case "mysql":case "mariadb":return `\`${s}\`.*`;case "postgres":case "cockroachdb":case "sqlite":return `"${s}".*`;case "mssql":return `[${s}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let l=this.modelColumnsMap.get(a)?.databaseName??H(a,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${s}\`.\`${l}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${s}"."${l}"`;case "mssql":return `[${s}].[${l}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??H(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}resolveComputedExpression(t){let e=t.includes(".")?t.split(".").pop():t;return this.modelColumnsMap.get(e)?.expression}isComputedColumn(t){return !!this.modelColumnsMap.get(t)?.expression}filterComputedColumns(t){return this.modelColumnsMap.size===0?t:t.filter(e=>!this.isComputedColumn(e))}stripComputedFromData(t){if(this.modelColumnsMap.size===0)return t;let e={};for(let r of Object.keys(t))this.isComputedColumn(r)||(e[r]=t[r]);return e}formatStringColumnBare(t,e){let r=e.includes(".")?e.split(".")[1]:e;return this.formatStringColumn(t,r)}dialectEmitsReturning(t){switch(t){case "postgres":case "cockroachdb":case "sqlite":case "mssql":return true;default:return false}}shouldFetchNatively(t,e){if(!this.dialectEmitsReturning(t)||t==="mssql")return false;if(t==="sqlite"&&e==="update"){for(let r of this.modelColumnsMap.values())if(r.autoUpdate)return false}return true}hasComputedColumn(t){return t.some(e=>this.isComputedColumn(e))}resolveColumnAlias(t,e){let r=this.modelColumnsMap.get(e);if(!r||r.columnName===r.databaseName)return "";switch(t){case "mssql":return ` as [${r.columnName}]`;case "mysql":case "mariadb":return ` as \`${r.columnName}\``;case "postgres":case "cockroachdb":case "sqlite":return ` as "${r.columnName}"`;default:return ""}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";return e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),`${e.split(".").map(o=>this.quoteIdentifier(t,o)).join(".")}${r?` as ${this.quoteIdentifier(t,r)}`:""}`}quoteIdentifier(t,e){switch(t){case "mysql":case "mariadb":return `\`${e}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${e}"`;case "mssql":return `[${e}]`;default:return e}}formatRawPlaceholders(t,e,r=[],n=1){if(!r.length)return {sql:e,bindings:[]};let o=n;return {sql:e.replace(/\?/g,()=>{switch(t){case "postgres":case "cockroachdb":return `$${o++}`;case "mssql":return `@${o++}`;default:return "?"}}),bindings:r}}prepareColumns(t,e,r="insert",n="postgres"){if(!t.length)return {columns:t,values:e};let o=[],s=[];for(let l=0;l<t.length;l++){let u=t[l],d=e[l];u!=="*"&&(o.push(u),s.push(d));}let a=n==="mysql"||n==="mariadb";for(let l=0;l<o.length;l++){let u=o[l],d=s[l],c=this.modelColumnsMap.get(u);if(c?.expression){o.splice(l,1),s.splice(l,1),l--;continue}if(!(d instanceof N)){if(!c){bh(d)&&(s[l]=JSON.stringify(d));continue}if(d==null&&(c.autoCreate===true||c.type==="uuid"&&n!=="mysql"&&n!=="mariadb")){o.splice(l,1),s.splice(l,1),l--;continue}if(c.prepare){let m=r==="insert"?c.prepare(d):c.prepare(d)??d;if(m!==null&&typeof m?.then=="function")throw new Error(`hysteria-orm: prepare on column "${u}" on model "${this.model.name}" returned a Promise, but prepare must be synchronous.`);s[l]=m;}n==="sqlite"&&s[l]instanceof Date&&eo(c)&&(s[l]=de(s[l],"ISO","UTC"));}}if(r==="insert"){let l=new Set(t);for(let u of this.jsInsertColumns)l.has(u.columnName)||this.generateJsInsertColumn(u,o,s,n);if(a){let u=this.model.primaryKey;if(u){let d=this.modelColumnsMap.get(u);d&&d.type==="uuid"&&d.isPrimary&&!l.has(u)&&this.generateJsInsertColumn(d,o,s,n);}}}else {let l=new Set(t);for(let u of this.autoUpdateColumns){if(l.has(u.columnName))continue;let d=u.prepare?.(new Date);if(d!=null){if(typeof d?.then=="function")throw new Error(`hysteria-orm: prepare on column "${u.columnName}" on model "${this.model.name}" returned a Promise, but prepare must be synchronous.`);o.push(u.columnName),s.push(n==="sqlite"&&d instanceof Date&&eo(u)?de(d,"ISO","UTC"):d);}}}return {columns:o,values:s}}generateJsInsertColumn(t,e,r,n){let o=t.prepare?.(void 0);if(o!==null&&typeof o?.then=="function")throw new Error(`hysteria-orm: prepare on column "${t.columnName}" on model "${this.model.name}" returned a Promise, but prepare must be synchronous.`);e.push(t.columnName),r.push(n==="sqlite"&&o instanceof Date&&eo(t)?de(o,"ISO","UTC"):o??void 0);}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new b(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var to=class{toSql(t){let e=t,n=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 gt){let d=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${d.newName}'`,bindings:[]}}let o=new b(this.model,"mssql"),s=[],a=[];for(let d of e.children){let{sql:c,bindings:m}=o.parse([d]);s.push(c.trim()),a.push(...m);}let l=s.join(", ");return {sql:`${n} ${l}`,bindings:a}}},Ku=new to;var ro=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},Qu=new ro;var no=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},Lu=new no;var oo=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},Wu=new oo;var so=class{toSql(t){let e=t;return g.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},ju=new so;var io=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},Fu=new io;var ao=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},Uu=new ao;var lo=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},Vu=new lo;var x=class extends N{constructor(e,r){super("raw",true);this.canKeywordBeSeenMultipleTimes=true;this.chainsWith=" ";this.currParamIndex=0;this.isRawValue=true;this.folder="raw";this.file="raw";this.rawValue=e,this.bindings=r;}};var P=class extends N{constructor(e,r=[]){super("sqlfunc");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="sqlfunc";this.file="sqlfunc";this.fn=e,this.args=r;}};var Ju=new Map;function je(i,t){let e=i===void 0?void 0:Ju.get(i),r=Ju.get("*");return e?.(t)??r?.(t)}var uo=class{toSql(t){let e=t,r;return e.defaultValue instanceof x?r=e.defaultValue.rawValue:e.defaultValue instanceof P?r=new b(this.model,"mssql").parse([e.defaultValue],1,true).sql: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:[]}}},Hu=new uo;var co=class{toSql(t){let e=t;return g.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},zu=new co;var mo=class{toSql(t){return {sql:"",bindings:[]}}},Gu=new mo;function po(i){return i.replace(/^[`"]|[`"]$/g,"")}function fo(i,t,e){if(!i.includes(".")){let o=po(i);return `${t}.${o}`}let[r,n]=i.split(".");return r=po(r),n=po(n),r!==e?i:n==="*"?`${t}.*`:`${t}.${n}`}function C(i){return typeof i=="function"?i():i}var W=(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 n=0;n<i.length;n++)r[n]=W(i[n],t);return r}let e=Object.create(Object.getPrototypeOf(i)||{});t.set(i,e);for(let r of Object.getOwnPropertyNames(i)){let n=i[r];if(typeof n=="function"){e[r]=n;continue}e[r]=W(n,t);}return e};var yo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let n=new y(this.model).formatStringColumn("mssql",C(e.column)),o=e.dataType.toLowerCase();if(o==="char"){let a=e.length??1;return {sql:`${n} char(${a})`,bindings:[]}}if(o==="varchar"){let a=e.length??255;return {sql:`${n} varchar(${a})`,bindings:[]}}if(o==="text"||o==="longtext"||o==="mediumtext"||o==="tinytext")return {sql:`${n} varchar(max)`,bindings:[]};if(o==="uuid"){let a=e.isForeignKey?"":" default NEWID()";return {sql:`${n} uniqueidentifier${a}`,bindings:[]}}if(o==="ulid")return {sql:`${n} varchar(26)`,bindings:[]};if(o==="bigint")return e.autoIncrement?{sql:`${n} bigint identity(1,1)`,bindings:[]}:{sql:`${n} bigint`,bindings:[]};if(o==="tinyint")return {sql:`${n} tinyint`,bindings:[]};if(o==="smallint")return {sql:`${n} smallint`,bindings:[]};if(o==="mediumint")return {sql:`${n} int`,bindings:[]};if(o==="float"||o==="real")return {sql:`${n} real`,bindings:[]};if(o==="double")return {sql:`${n} float`,bindings:[]};if(o==="decimal"||o==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${n} decimal(${a}, ${l})`,bindings:[]}}if(o==="date")return {sql:`${n} date`,bindings:[]};if(o==="year")return {sql:`${n} smallint`,bindings:[]};if(o==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${n} time${a}`,bindings:[]}}if(o==="datetime"||o==="timestamp"){let a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${n} datetime2${a}`;return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,bindings:[]}}if(o==="boolean"||o==="bool")return {sql:`${n} bit`,bindings:[]};if(o==="bytea"||o==="binary"||o==="varbinary"||o==="blob"||o==="longblob"||o==="mediumblob"||o==="tinyblob")return {sql:`${n} varbinary(max)`,bindings:[]};if(o==="json"||o==="jsonb")return {sql:`${n} nvarchar(max)`,bindings:[]};if(o==="enum"){if(e.enumValues&&e.enumValues.length>0){let a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${n} varchar(255) check (${n} in (${a}))`,bindings:[]}}return {sql:`${n} varchar(255)`,bindings:[]}}if(o==="integer"||o==="int")return e.autoIncrement?{sql:`${n} int identity(1,1)`,bindings:[]}:{sql:`${n} int`,bindings:[]};if(o==="geometry")return {sql:`${n} geometry`,bindings:[]};if(o==="point")return {sql:`${n} geometry`,bindings:[]};if(o==="linestring")return {sql:`${n} geometry`,bindings:[]};if(o==="polygon")return {sql:`${n} geometry`,bindings:[]};if(o==="multipoint")return {sql:`${n} geometry`,bindings:[]};let s=e.length?`(${e.length})`:"";return {sql:`${n} ${o}${s}`,bindings:[]}}},Yu=new yo;var ho=class{toSql(t){let e=t.value;return {sql:e.startsWith("--")||e.startsWith("#")?`${e}
121
+ Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}let e=lr(this.logs);e?.customLogger&&g.setCustomLogger(e.customLogger);}handleCockroachdbSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||E.DB_DATABASE||":memory:",this.logs=t?.logs||E.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||E.MONGO_URL,this.logs=t?.logs||E.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=1433);}};var ch=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},mh=i=>i.openApi?.required??false,ph=i=>{let t=i.getColumns(),e={};for(let r of t)r.openApi?.excludeFromSwagger||(e[r.columnName]=ch(r));return e},fh=i=>{let t=i.getColumns(),e=[];for(let r of t)mh(r)&&e.push(r.columnName);return e||[]},yh=i=>{let t=ph(i),e=fh(i);return {type:"object",properties:t,required:e.length?e:[]}};var vu=i=>i.map(t=>({...yh(t),modelName:t.table,$id:t.table}));var Hn=(i,t)=>{let e=Pe.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var zn=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:n}=r.parse([e.column]),o=e.inlineConstraints;if(o&&o.length){let s=[];for(let a of o){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(n+=` ${s.join(" ")}`);}return {sql:`add ${n}`,bindings:[]}}},Iu=new zn;var Gn=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:n}=r.parse([e.constraint]);return {sql:`add ${n}`,bindings:[]}}},Pu=new Gn;var Yn=class{toSql(t){return {sql:`add primary key (${t.columns.map(n=>`[${n}]`).join(", ")})`,bindings:[]}}},Eu=new Yn;var Zn=class{toSql(t){let e=t,r=new b(this.model,"mssql"),{sql:n}=r.parse([e.newType]),[,...o]=n.trim().split(/\s+/),s=o.join(" ");e.newType.dataType==="uuid"&&(s=s.replace(/\s+default\s+.+$/i,"").trim());let 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:[]}}},Bu=new Zn;var N=class{constructor(t,e=false){this.currParamIndex=1;this.isRawValue=false;this.keyword=t,this.isRawValue=e;}};var gt=class extends N{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};function gr(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 br(i){return typeof i!="string"||!i?i:i.replace(/([-_][a-z])/g,t=>t.toUpperCase().replace("-","").replace("_",""))}function Xn(i){if(typeof i!="string"||!i)return i;let t=br(i);return t.charAt(0).toUpperCase()+t.slice(1)}function z(i,t){return t==="preserve"?i:t==="snake"?gr(i):t==="camel"?br(i):t==="pascal"?Xn(i):t instanceof RegExp?i.replace(t,e=>e[1].toUpperCase()):t(i)}function xe(i){return String(i).padStart(2,"0")}function gh(i,t){let e=i.getFullYear(),r=xe(i.getMonth()+1),n=xe(i.getDate()),o=xe(i.getHours()),s=xe(i.getMinutes()),a=xe(i.getSeconds());switch(t){case "ISO":return `${e}-${r}-${n} ${o}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${n}`;case "TIME_ONLY":return `${o}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}function ku(i,t){let e=i.getUTCFullYear(),r=xe(i.getUTCMonth()+1),n=xe(i.getUTCDate()),o=xe(i.getUTCHours()),s=xe(i.getUTCMinutes()),a=xe(i.getUTCSeconds());switch(t){case "ISO":return `${e}-${r}-${n} ${o}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${n}`;case "TIME_ONLY":return `${o}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}var de=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");return e==="LOCAL"?gh(i,t):ku(i,t)};var bt=(i=new Date)=>ku(i,"ISO");var bh=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},eo=i=>!i.expression&&(i.type==="date"||i.type==="datetime"||i.type==="timestamp"),y=class{constructor(t){this.model=t;this.modelColumnsMap=typeof t.getColumnsByName=="function"?t.getColumnsByName():new Map;let e=[],r=[];for(let n of this.modelColumnsMap.values())n.expression||((n.type==="ulid"||n.autoCreate==="js")&&e.push(n),n.autoUpdate&&r.push(n));this.jsInsertColumns=e,this.autoUpdateColumns=r;}formatStringColumn(t,e){if(e==="*")return "*";let r=this.resolveComputedExpression(e);if(r!==void 0)return `(${r})`;if(e.includes(".")){let[s,a]=e.split(".");if(a==="*")switch(t){case "mysql":case "mariadb":return `\`${s}\`.*`;case "postgres":case "cockroachdb":case "sqlite":return `"${s}".*`;case "mssql":return `[${s}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let l=this.modelColumnsMap.get(a)?.databaseName??z(a,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${s}\`.\`${l}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${s}"."${l}"`;case "mssql":return `[${s}].[${l}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??z(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}resolveComputedExpression(t){let e=t.includes(".")?t.split(".").pop():t;return this.modelColumnsMap.get(e)?.expression}isComputedColumn(t){return !!this.modelColumnsMap.get(t)?.expression}filterComputedColumns(t){return this.modelColumnsMap.size===0?t:t.filter(e=>!this.isComputedColumn(e))}stripComputedFromData(t){if(this.modelColumnsMap.size===0)return t;let e={};for(let r of Object.keys(t))this.isComputedColumn(r)||(e[r]=t[r]);return e}formatStringColumnBare(t,e){let r=e.includes(".")?e.split(".")[1]:e;return this.formatStringColumn(t,r)}dialectEmitsReturning(t){switch(t){case "postgres":case "cockroachdb":case "sqlite":case "mssql":return true;default:return false}}shouldFetchNatively(t,e){if(!this.dialectEmitsReturning(t)||t==="mssql")return false;if(t==="sqlite"&&e==="update"){for(let r of this.modelColumnsMap.values())if(r.autoUpdate)return false}return true}hasComputedColumn(t){return t.some(e=>this.isComputedColumn(e))}resolveColumnAlias(t,e){let r=this.modelColumnsMap.get(e);if(!r||r.columnName===r.databaseName)return "";switch(t){case "mssql":return ` as [${r.columnName}]`;case "mysql":case "mariadb":return ` as \`${r.columnName}\``;case "postgres":case "cockroachdb":case "sqlite":return ` as "${r.columnName}"`;default:return ""}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";return e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),`${e.split(".").map(o=>this.quoteIdentifier(t,o)).join(".")}${r?` as ${this.quoteIdentifier(t,r)}`:""}`}quoteIdentifier(t,e){switch(t){case "mysql":case "mariadb":return `\`${e}\``;case "postgres":case "cockroachdb":case "sqlite":return `"${e}"`;case "mssql":return `[${e}]`;default:return e}}formatRawPlaceholders(t,e,r=[],n=1){if(!r.length)return {sql:e,bindings:[]};let o=n;return {sql:e.replace(/\?/g,()=>{switch(t){case "postgres":case "cockroachdb":return `$${o++}`;case "mssql":return `@${o++}`;default:return "?"}}),bindings:r}}prepareColumns(t,e,r="insert",n="postgres"){if(!t.length)return {columns:t,values:e};let o=[],s=[];for(let l=0;l<t.length;l++){let u=t[l],d=e[l];u!=="*"&&(o.push(u),s.push(d));}let a=n==="mysql"||n==="mariadb";for(let l=0;l<o.length;l++){let u=o[l],d=s[l],c=this.modelColumnsMap.get(u);if(c?.expression){o.splice(l,1),s.splice(l,1),l--;continue}if(!(d instanceof N)){if(!c){bh(d)&&(s[l]=JSON.stringify(d));continue}if(d==null&&(c.autoCreate===true||c.type==="uuid"&&n!=="mysql"&&n!=="mariadb")){o.splice(l,1),s.splice(l,1),l--;continue}if(c.prepare){let m=r==="insert"?c.prepare(d):c.prepare(d)??d;if(m!==null&&typeof m?.then=="function")throw new Error(`hysteria-orm: prepare on column "${u}" on model "${this.model.name}" returned a Promise, but prepare must be synchronous.`);s[l]=m;}n==="sqlite"&&s[l]instanceof Date&&eo(c)&&(s[l]=de(s[l],"ISO","UTC"));}}if(r==="insert"){let l=new Set(t);for(let u of this.jsInsertColumns)l.has(u.columnName)||this.generateJsInsertColumn(u,o,s,n);if(a){let u=this.model.primaryKey;if(u){let d=this.modelColumnsMap.get(u);d&&d.type==="uuid"&&d.isPrimary&&!l.has(u)&&this.generateJsInsertColumn(d,o,s,n);}}}else {let l=new Set(t);for(let u of this.autoUpdateColumns){if(l.has(u.columnName))continue;let d=u.prepare?.(new Date);if(d!=null){if(typeof d?.then=="function")throw new Error(`hysteria-orm: prepare on column "${u.columnName}" on model "${this.model.name}" returned a Promise, but prepare must be synchronous.`);o.push(u.columnName),s.push(n==="sqlite"&&d instanceof Date&&eo(u)?de(d,"ISO","UTC"):d);}}}return {columns:o,values:s}}generateJsInsertColumn(t,e,r,n){let o=t.prepare?.(void 0);if(o!==null&&typeof o?.then=="function")throw new Error(`hysteria-orm: prepare on column "${t.columnName}" on model "${this.model.name}" returned a Promise, but prepare must be synchronous.`);e.push(t.columnName),r.push(n==="sqlite"&&o instanceof Date&&eo(t)?de(o,"ISO","UTC"):o??void 0);}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new b(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var to=class{toSql(t){let e=t,n=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 gt){let d=e.children[0];return {sql:`EXEC sp_rename '${e.table}', '${d.newName}'`,bindings:[]}}let o=new b(this.model,"mssql"),s=[],a=[];for(let d of e.children){let{sql:c,bindings:m}=o.parse([d]);s.push(c.trim()),a.push(...m);}let l=s.join(", ");return {sql:`${n} ${l}`,bindings:a}}},Ku=new to;var ro=class{toSql(t){return {sql:`drop column [${t.column}]`,bindings:[]}}},Qu=new ro;var no=class{toSql(t){return {sql:`drop constraint [${t.constraintName}]`,bindings:[]}}},Lu=new no;var oo=class{toSql(t){return {sql:`drop constraint DF_${t.column}`,bindings:[]}}},Wu=new oo;var so=class{toSql(t){let e=t;return g.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] null`,bindings:[]}}},ju=new so;var io=class{toSql(t){return {sql:`drop constraint [${`pk_${t.table}`}]`,bindings:[]}}},Fu=new io;var ao=class{toSql(t){let e=t;return {sql:`sp_rename '${this.model?.table??""}.${e.oldName}', '${e.newName}', 'COLUMN'`,bindings:[]}}},Uu=new ao;var lo=class{toSql(t){return {sql:`[${t.newName}]`,bindings:[]}}},Vu=new lo;var x=class extends N{constructor(e,r){super("raw",true);this.canKeywordBeSeenMultipleTimes=true;this.chainsWith=" ";this.currParamIndex=0;this.isRawValue=true;this.folder="raw";this.file="raw";this.rawValue=e,this.bindings=r;}};var P=class extends N{constructor(e,r=[]){super("sqlfunc");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="sqlfunc";this.file="sqlfunc";this.fn=e,this.args=r;}};var Ju=new Map;function je(i,t){let e=i===void 0?void 0:Ju.get(i),r=Ju.get("*");return e?.(t)??r?.(t)}var uo=class{toSql(t){let e=t,r;return e.defaultValue instanceof x?r=e.defaultValue.rawValue:e.defaultValue instanceof P?r=new b(this.model,"mssql").parse([e.defaultValue],1,true).sql: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:[]}}},Hu=new uo;var co=class{toSql(t){let e=t;return g.warn("MSSQL requires the full column type when altering nullability. This operation may need manual adjustment."),{sql:`alter column [${e.column}] not null`,bindings:[]}}},zu=new co;var mo=class{toSql(t){return {sql:"",bindings:[]}}},Gu=new mo;function po(i){return i.replace(/^[`"]|[`"]$/g,"")}function fo(i,t,e){if(!i.includes(".")){let o=po(i);return `${t}.${o}`}let[r,n]=i.split(".");return r=po(r),n=po(n),r!==e?i:n==="*"?`${t}.*`:`${t}.${n}`}function C(i){return typeof i=="function"?i():i}var W=(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 n=0;n<i.length;n++)r[n]=W(i[n],t);return r}let e=Object.create(Object.getPrototypeOf(i)||{});t.set(i,e);for(let r of Object.getOwnPropertyNames(i)){let n=i[r];if(typeof n=="function"){e[r]=n;continue}e[r]=W(n,t);}return e};var yo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let n=new y(this.model).formatStringColumn("mssql",C(e.column)),o=e.dataType.toLowerCase();if(o==="char"){let a=e.length??1;return {sql:`${n} char(${a})`,bindings:[]}}if(o==="varchar"){let a=e.length??255;return {sql:`${n} varchar(${a})`,bindings:[]}}if(o==="text"||o==="longtext"||o==="mediumtext"||o==="tinytext")return {sql:`${n} varchar(max)`,bindings:[]};if(o==="uuid"){let a=e.isForeignKey?"":" default NEWID()";return {sql:`${n} uniqueidentifier${a}`,bindings:[]}}if(o==="ulid")return {sql:`${n} varchar(26)`,bindings:[]};if(o==="bigint")return e.autoIncrement?{sql:`${n} bigint identity(1,1)`,bindings:[]}:{sql:`${n} bigint`,bindings:[]};if(o==="tinyint")return {sql:`${n} tinyint`,bindings:[]};if(o==="smallint")return {sql:`${n} smallint`,bindings:[]};if(o==="mediumint")return {sql:`${n} int`,bindings:[]};if(o==="float"||o==="real")return {sql:`${n} real`,bindings:[]};if(o==="double")return {sql:`${n} float`,bindings:[]};if(o==="decimal"||o==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${n} decimal(${a}, ${l})`,bindings:[]}}if(o==="date")return {sql:`${n} date`,bindings:[]};if(o==="year")return {sql:`${n} smallint`,bindings:[]};if(o==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${n} time${a}`,bindings:[]}}if(o==="datetime"||o==="timestamp"){let a=typeof e.precision=="number"?`(${e.precision})`:"",l=`${n} datetime2${a}`;return e.autoCreate&&(l+=" default current_timestamp"),{sql:l,bindings:[]}}if(o==="boolean"||o==="bool")return {sql:`${n} bit`,bindings:[]};if(o==="bytea"||o==="binary"||o==="varbinary"||o==="blob"||o==="longblob"||o==="mediumblob"||o==="tinyblob")return {sql:`${n} varbinary(max)`,bindings:[]};if(o==="json"||o==="jsonb")return {sql:`${n} nvarchar(max)`,bindings:[]};if(o==="enum"){if(e.enumValues&&e.enumValues.length>0){let a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${n} varchar(255) check (${n} in (${a}))`,bindings:[]}}return {sql:`${n} varchar(255)`,bindings:[]}}if(o==="integer"||o==="int")return e.autoIncrement?{sql:`${n} int identity(1,1)`,bindings:[]}:{sql:`${n} int`,bindings:[]};if(o==="geometry")return {sql:`${n} geometry`,bindings:[]};if(o==="point")return {sql:`${n} geometry`,bindings:[]};if(o==="linestring")return {sql:`${n} geometry`,bindings:[]};if(o==="polygon")return {sql:`${n} geometry`,bindings:[]};if(o==="multipoint")return {sql:`${n} geometry`,bindings:[]};let s=e.length?`(${e.length})`:"";return {sql:`${n} ${o}${s}`,bindings:[]}}},Yu=new yo;var ho=class{toSql(t){let e=t.value;return {sql:e.startsWith("--")||e.startsWith("#")?`${e}
122
122
  `:e,bindings:[]}}},Zu=new ho;var go=class{toSql(t){return {sql:"",bindings:[]}}},Xu=new go;var bo=class{toSql(t){let e=t,r=new y(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let n=e.constraintName?`constraint [${e.constraintName}] `:"",o=(e.columns??[]).map(s=>r.formatStringColumn("mssql",C(s))).join(", ");return {sql:`${n}primary key (${o})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let n=e.columns??[],o=e.constraintName?`constraint [${e.constraintName}] `:"",s=n.map(a=>r.formatStringColumn("mssql",C(a))).join(", ");return e.constraintName?{sql:`${o}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 n=e.defaultValue;return n instanceof x?{sql:`default ${n.rawValue}`,bindings:[]}:n instanceof P?{sql:`default ${new b(this.model,"mssql").parse([n],1,true).sql}`,bindings:[]}:n==="NULL"||n===null?{sql:"default null",bindings:[]}:n==="TRUE"?{sql:"default 1",bindings:[]}:n==="FALSE"?{sql:"default 0",bindings:[]}:typeof n=="string"?{sql:`default '${n}'`,bindings:[]}:{sql:`default ${n}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let n=e.columns.map(u=>r.formatStringColumn("mssql",C(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let o=r.formatStringTable("mssql",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("mssql",C(u))).join(", "),l=`${e.constraintName?`constraint [${e.constraintName}] `:""}foreign key (${n}) references ${o}(${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:[]}}},ed=new bo;var To=class{toSql(t){let e=t,n=new y(this.model).formatStringTable("mssql",e.table);if(!e.children||!e.children.length)return {sql:`${n} ()`,bindings:[]};let o=new b(this.model,"mssql"),s=[],a=[];for(let h of e.children){let{sql:f,bindings:T}=o.parse([h]);if(h.folder==="constraint"){let w=s.pop()??"",q=f;if(/not null/i.test(q)||/null/i.test(q)||/default/i.test(q)){let D=`${w} ${q}`.trim();D=D.replace(/(references\s+\[[^\]]+\]\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(D),a.push(...T);continue}s.push(w),s.push(q),a.push(...T);continue}s.push(f),a.push(...T);}for(let h of e.namedConstraints){let{sql:f,bindings:T}=o.parse([h]);s.push(f),a.push(...T);}let l=s.join(", "),u=[];e.dataCompression&&u.push(`DATA_COMPRESSION = ${e.dataCompression}`);let d=e.onFilegroup?` ON [${e.onFilegroup}]`:"",c=e.textImageOn?` TEXTIMAGE_ON [${e.textImageOn}]`:"",m=u.length>0?` WITH (${u.join(", ")})`:"";return {sql:`${n} (${l})${m}${d}${c}`,bindings:a}}},td=new To;var wo=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new y(this.model).getFromForWriteOperations("mssql",e.fromNode),bindings:[]}}},rd=new wo;var So=class{toSql(t){return {sql:"",bindings:[]}}},nd=new So;var No=class{toSql(t){return g.warn("MSSQL does not support DISTINCT ON. This clause will be ignored."),{sql:"",bindings:[]}}},od=new No;var qo=class{toSql(t){let e=t,n=new y(this.model).formatStringTable("mssql",e.table);return {sql:`${e.ifExists?"if exists ":""}${n}`,bindings:[]}}},sd=new qo;var Co=class{toSql(t){return {sql:`-- MSSQL does not support extensions (extension: ${t.extensionName})`,bindings:[]}}},id=new Co;var Ro=class{toSql(t){let e=t,r=new y(this.model),n=e.alias?` as ${r.quoteIdentifier("mssql",e.alias)}`:"";if(e.table instanceof x){let{sql:l,bindings:u}=r.formatRawPlaceholders("mssql",e.table.rawValue,e.table.bindings??[],e.currParamIndex);return {sql:`${l}${n}`,bindings:u}}if(typeof e.table=="string")return {sql:`${r.formatStringTable("mssql",e.schema?`${e.schema}.${e.table}`:e.table)}${n}`,bindings:[]};let o=Array.isArray(e.table)?e.table:[e.table],a=new b(this.model,"mssql").parse(o);return {sql:`(${a.sql})${n}`,bindings:a.bindings}}},ad=new Ro;var _o=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new y(this.model).formatStringColumn("mssql",e.column),bindings:[]}}},ld=new _o;var Mo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,n=new b(this.model,"mssql"),o=new y(this.model);if(e.group?.length){let{sql:u,bindings:d}=n.parse(e.group,e.currParamIndex,true);return {sql:`(${u})`,bindings:d}}let s=o.formatStringColumn("mssql",e.column),a="",l=[];if(e.subquery!==void 0){let u=this.parseSubquery(n,e,r);a=`${e.column?`${s} `:""}${e.operator} (${u.sql})`,l=u.bindings;}else if(e.value instanceof P){let u=n.parse([e.value],1,true).sql;a=`${s} ${e.operator} ${u}`;}else if(e.operator==="is null"||e.operator==="is not null")a=`${s} ${e.operator}`;else if(Array.isArray(e.value)){if(e.operator==="between"||e.operator==="not between")a=`${s} ${e.operator} @${r} and @${r+1}`;else {let u=e.value.map((d,c)=>`@${r+c}`).join(", ");a=`${s} ${e.operator} (${u})`;}l=e.value;}else a=`${s} ${e.operator} @${r}`,l=[e.value];return e.isNegated&&(a=`not (${a})`),{sql:a.trim(),bindings:l}}parseSubquery(t,e,r){let n=e.subquery;if(typeof n=="string")return {sql:n,bindings:[]};let o=Array.isArray(n)?n:[n];return t.parse(o,r)}},ud=new Mo;var xo=class{toSql(t){let e=t,n=new y(this.model).formatStringTable("mssql",e.table),o=e.columns.map(a=>`[${a}]`).join(", ");return {sql:`${e.unique?"unique ":""}[${e.indexName}] on ${n} (${o})`,bindings:[]}}},dd=new xo;var Oo=class{toSql(t){let e=t;return {sql:`[${e.indexName}] on [${e.table}]`,bindings:[]}}},cd=new Oo;var Do=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new y(this.model),n=r.getFromForWriteOperations("mssql",e.fromNode);if(!e.records.length)return {sql:n,bindings:[]};let o=e.records[0],s=Object.keys(o).filter(m=>o[m]!==void 0);if(!s.length)return {sql:n,bindings:[]};let a=s.map(m=>r.formatStringColumn("mssql",m)).join(", "),l=[],u=[],d=e.currParamIndex;for(let m of e.records){let p=s.map(f=>m[f]),h=[];for(let f of p)f instanceof x?h.push(f.rawValue):(l.push(f),h.push(`@${d++}`));u.push(`(${h.join(", ")})`);}let c=`${n} (${a}) values ${u.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let m=e.returning.map(p=>`inserted.${r.formatStringColumn("mssql",p)}${r.resolveColumnAlias("mssql",p)}`).join(", ");c=c.replace(") values",`) output ${m} values`);}else {let m=this.getOutputColumns(s,r);c=c.replace(") values",`) output ${m} values`);}return {sql:c,bindings:l}}getOutputColumns(t,e){let r=[...t],n=this.model.primaryKey;return n&&!t.includes(n)&&r.push(n),r.map(o=>`inserted.${e.formatStringColumn("mssql",o)}${e.resolveColumnAlias("mssql",o)}`).join(", ")}},md=new Do;var Ao=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};if(e.using?.length)throw new S("JoinQueryBuilder::using","USING_NOT_SUPPORTED_IN_MSSQL");let r=new y(this.model),n=r.formatStringTable("mssql",e.schema?`${e.schema}.${e.table}`:e.table);if(e.type==="cross")return {sql:n,bindings:[]};let o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let s=e.right;s.includes(".")||(s=`${this.model.table}.${s}`);let a=r.formatStringColumn("mssql",o),l=r.formatStringColumn("mssql",s),u=`${n} on ${a} ${e.on?.operator} ${l}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let c=new b(this.model,"mssql");for(let m of e.additionalConditions){let p=c.parse([m]);if(p.sql){let h=p.sql.replace(/^where\s+/i,"");u+=` and ${h}`,d.push(...p.bindings);}}}return {sql:u,bindings:d}}},pd=new Ao;var Kt=class extends N{constructor(e,r,n,o,s){super("json_mutation");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="json_mutation";this.file="json_mutation";this.operation=e,this.column=r,this.path=n,this.value=o,this.alias=s;}},fd=(i,t,e,r)=>new Kt("set",i,t,e,r),yd=(i,t,e,r)=>new Kt("insert",i,t,e,r),hd=(i,t,e)=>new Kt("remove",i,t,void 0,e),Th=/^[A-Za-z_][A-Za-z0-9_]*$/;function gd(i){if(Array.isArray(i))return i;let t=[],e=i.replace(/^\$/,""),r=/\.([^.[\]]+)|\[(\d+)\]/g,n;for(;(n=r.exec(e))!==null;)n[1]!==void 0?t.push(n[1]):t.push(Number(n[2]));return t}function Tt(i){return "$"+gd(i).map(e=>typeof e=="number"?`[${e}]`:Th.test(e)?`.${e}`:`["${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"]`).join("")}function bd(i){return `'{${gd(i).map(r=>{let n=String(r);return /^[A-Za-z0-9_]+$/.test(n)?n:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}).join(",")}}'`}var $o=class{toSql(t){let e=t;if(e.operation!=="set")throw new S("MssqlJsonMutationInterpreter::toSql","NOT_SUPPORTED_IN_MSSQL",new Error(`json${e.operation==="insert"?"Insert":"Remove"} is not supported by mssql; only jsonSet (JSON_MODIFY) is`));let r=new y(this.model).formatStringColumn("mssql",e.column),n=`'${Tt(e.path).replace(/'/g,"''")}'`,o=e.value!==null&&typeof e.value=="object",s=`JSON_MODIFY(${r}, ${n}, @${e.currParamIndex})`;return {sql:this.withAlias(s,e.alias),bindings:[o?JSON.stringify(e.value):e.value]}}withAlias(t,e){return e?`${t} as [${e}]`:t}},Td=new $o;var vo=class{toSql(t){let e=t;return {sql:`fetch next @${e.currParamIndex} rows only`,bindings:[e.limit]}}},wd=new vo;var Io=class{toSql(t){return {sql:"",bindings:[]}}},Sd=new Io;var Po=class{toSql(t){let e=t;return {sql:`offset @${e.currParamIndex} rows`,bindings:[e.offset]}}},Nd=new Po;var Eo=class{toSql(t){let e=t;return e.isRawValue?{sql:e.table,bindings:[]}:(g.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:[]})}},qd=new Eo;var Bo=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new y(this.model).formatStringColumn("mssql",e.column),n=e.direction.toLowerCase();return {sql:`${r} ${n}`,bindings:[]}}},Cd=new Bo;var ko=class{toSql(t){let e=t;return {sql:e.rawValue,bindings:e.bindings??[]}}},Rd=new ko;var Ko=class{toSql(t){let e=t,r=new y(this.model);return {sql:`output ${!e.columns.length||e.columns.includes("*")?`${e.prefix}.*`:e.columns.map(o=>`${e.prefix}.${r.formatStringColumn("mssql",o)}${r.resolveColumnAlias("mssql",o)}`).join(", ")}`,bindings:[]}}},_d=new Ko;var Qo=class{toSql(t){return {sql:`SELECT
123
123
  cc.name AS name,
124
124
  cc.definition AS expression
@@ -256,7 +256,7 @@ ORDER BY ordinal_position`,bindings:[]}}},op=new ga;var ba=class{toSql(t){let e=
256
256
  FROM pragma_table_info('${t.table}')
257
257
  WHERE pk > 0
258
258
  ORDER BY pk`,bindings:[]}}},pf=new Rl;var _l=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},ff=new _l;var Ml=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction,e.distinct),n=this.formatAlias(e.alias);return {sql:`${r.sql}${n}`,bindings:r.bindings}}formatColumn(t,e,r){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("sqlite",t),s=o;return e&&(s=`${e.toLowerCase()}(${r?"DISTINCT ":""}${o})`),{sql:s,bindings:[]}}if(Array.isArray(t)&&t.length>0){let s=new b(this.model,"sqlite").parse(t),a=`(${s.sql})`;return e&&(a=`${e.toLowerCase()}${a}`),{sql:a,bindings:s.bindings}}if(!Array.isArray(t)){let s=new b(this.model,"sqlite").parse([t],void 0,true),a=`(${s.sql})`;return e&&(a=`${e.toLowerCase()}${a}`),{sql:a,bindings:s.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let u=new y(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${u})`:u}let l=`(${new b(this.model,"sqlite").parse([o]).sql})`;return e&&(l=`${e.toLowerCase()}${l}`),l}).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,n)=>{let o=t.slice(0,n),s=o.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=o.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},yf=new Ml;var xl=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),n=te.from(e.jsonPath),o="";switch(e.jsonOperator){case "extract":o=this.buildExtractSql(r,n);break;case "extract_text":o=this.buildExtractTextSql(r,n);break;case "array_length":o=this.buildArrayLengthSql(r,n);break;case "object_keys":o=this.buildObjectKeysSql(r,n);break;case "raw":o=e.column;break}return {sql:this.formatWithAlias(o,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}},hf=new xl;var Ol=class{toSql(t){let e=t,r=je(this.dbType,e);if(r!==void 0)return {sql:r,bindings:[]};let n=this.renderToken(e.fn);if(n!==void 0)return {sql:n,bindings:[]};let o=e.args.map(s=>s instanceof x?s.rawValue:s instanceof P?this.toSql(s).sql:typeof s=="number"?String(s):`'${s}'`).join(", ");return {sql:`${e.fn}(${o})`,bindings:[]}}renderToken(t){switch(t){case "$uuid":return "lower(hex(randomblob(16)))";case "$now":case "$currentTimestamp":return "current_timestamp";default:return}}},gf=new Ol;var Dl=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:[]}}},bf=new Dl;var Al=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),n=Array.isArray(e.query)?e.query:[e.query],o=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(n.filter(Boolean),e.currParamIndex);return {sql:o.sql,bindings:o.bindings}}},Tf=new Al;var $l=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),n=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:n,bindings:[]};let o=[],s=e.currParamIndex,a=e.columns.map((l,u)=>{let d=e.values[u],c=r.formatStringColumn("sqlite",l);if(d instanceof x)return `${c} = ${d.rawValue}`;if(d instanceof N){let m=new b(this.model,"sqlite").parse([d],s,true);return o.push(...m.bindings),s+=m.bindings.length,`${c} = ${m.sql}`}return o.push(d),`${c} = ?`}).join(", ");return {sql:`${n} set ${a}`,bindings:o}}},wf=new $l;var vl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",n=[];if(this.isRawNode(e.value)){let o=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${o}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new y(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,n=e.value;else {let o=e.value.map(s=>"?").join(", ");r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${o})`,n=e.value;}else if(e.value instanceof P){let o=new b(this.model,"sqlite").parse([e.value],1,true).sql;r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${o}`,n=[];}else if(e.operator.includes("null"))r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,n=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.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("sqlite",t):t}},Sf=new vl;var Il=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"sqlite"),{sql:n,bindings:o}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${n})`,bindings:o}}},Nf=new Il;var Pl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",n=[],o=new y(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${o}) = json(?)`,n=[JSON.stringify(e.value)];break;case "contains":r=`json(${o}) = json(?)`,n=[JSON.stringify(e.value)];break;case "not contains":r=`json(${o}) = json(?)`,n=[JSON.stringify(e.value)];break;case "path":{let s=te.from(e.path??"");r=`json_extract(${o}, '${s.toSqlite()}') ${e.comparisonOperator??"="} ?`,n=[e.value];break}case "subset":case "has none":throw new S("WhereJsonInterpreter::unsupported","NOT_SUPPORTED_IN_SQLITE");case "raw":r=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:n}}},qf=new Pl;var El=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:n}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:n}}handleObjectSubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:n}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:n}}},Cf=new El;var Bl=class{toSql(t){let e=t,r=new y(this.model),n=s=>r.formatStringColumn("sqlite",s),o=[];return e.partitionBy.length&&o.push(`partition by ${e.partitionBy.map(n).join(", ")}`),e.orderBy.length&&o.push(`order by ${e.orderBy.map(s=>s.order?`${n(s.column)} ${s.order}`:n(s.column)).join(", ")}`),{sql:`${e.fn}() over (${o.join(" ")})`,bindings:[]}}},Rf=new Bl;var kl=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),n=Array.isArray(e.body)?e.body:[e.body],o=r.parse(n.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${o.sql})`,bindings:o.bindings}}},_f=new kl;var Kl={mssql:{alter_table:{add_column:Iu,add_constraint:Pu,add_primary_key:Eu,alter_column_type:Bu,alter_table:Ku,drop_column:Qu,drop_constraint:Lu,drop_default:Wu,drop_not_null:ju,drop_primary_key:Fu,rename_column:Uu,rename_table:Vu,set_default:Hu,set_not_null:zu,set_table_options:Gu},column:{column_type:Yu},comment:{comment:Zu},constraint:{after:Xu,constraint:ed},create_table:{create_table:td},delete:{delete:rd},distinct:{distinct:nd,distinct_on:od},drop_table:{drop_table:sd},extension:{create_extension:id},from:{from:ad},group_by:{group_by:ld},having:{having:ud},index_op:{create_index:dd,drop_index:cd},insert:{insert:md},join:{join:pd},json_mutation:{json_mutation:Td},limit:{limit:wd},lock:{lock:Sd},offset:{offset:Nd},on_duplicate:{on_duplicate:qd},order_by:{order_by:Cd},raw:{raw:Rd},returning:{returning:_d},schema:{check_constraint_info:Md,foreign_key_info:xd,get_column_listing:Od,get_tables:Dd,has_check_constraint:Ad,has_column:$d,has_index:vd,has_primary_key:Id,has_table:Pd,index_info:Ed,primary_key_info:Bd,table_info:kd},select:{select:Kd,select_json:Qd},sqlfunc:{sqlfunc:Ld},truncate:{truncate:Wd},union:{union:jd},update:{update:Fd},where:{where:Ud,where_group:Vd,where_json:Jd,where_subquery:Hd},window:{window:zd},with:{with:Gd}},mysql:{alter_table:{add_column:Yd,add_constraint:Zd,add_primary_key:Xd,alter_column_type:ec,alter_table:tc,drop_column:rc,drop_constraint:nc,drop_default:oc,drop_not_null:sc,drop_primary_key:ic,rename_column:ac,rename_table:lc,set_default:uc,set_not_null:dc,set_table_options:cc},column:{column_type:mc},comment:{comment:pc},constraint:{after:fc,constraint:yc},create_table:{create_table:hc},delete:{delete:gc},distinct:{distinct:bc,distinct_on:Tc},drop_table:{drop_table:wc},extension:{create_extension:Sc},from:{from:Nc},group_by:{group_by:qc},having:{having:Cc},index_op:{create_index:Rc,drop_index:_c},insert:{insert:Mc},join:{join:xc},json_mutation:{json_mutation:Oc},limit:{limit:Dc},lock:{lock:Ac},offset:{offset:$c},on_duplicate:{on_duplicate:vc},order_by:{order_by:Ic},raw:{raw:Pc},returning:{returning:Ec},schema:{check_constraint_info:Bc,foreign_key_info:kc,get_column_listing:Kc,get_tables:Qc,has_check_constraint:Lc,has_column:Wc,has_index:jc,has_primary_key:Fc,has_table:Uc,index_info:Vc,primary_key_info:Jc,table_info:Hc},select:{select:zc,select_json:Gc},sqlfunc:{sqlfunc:Yc},truncate:{truncate:Zc},union:{union:Xc},update:{update:em},where:{where:tm,where_group:rm,where_json:nm,where_subquery:om},window:{window:sm},with:{with:im}},postgres:{alter_table:{add_column:am,add_constraint:lm,add_primary_key:um,alter_column_type:dm,alter_table:cm,drop_column:mm,drop_constraint:pm,drop_default:fm,drop_not_null:ym,drop_primary_key:hm,rename_column:gm,rename_table:bm,set_default:Tm,set_not_null:wm,set_table_options:Sm},column:{column_type:Nm},comment:{comment:qm},constraint:{after:Cm,constraint:Rm},create_table:{create_table:_m},delete:{delete:Mm},distinct:{distinct:xm,distinct_on:Om},drop_table:{drop_table:Dm},extension:{create_extension:Am},from:{from:$m},group_by:{group_by:vm},having:{having:Im},index_op:{create_index:Pm,drop_index:Em},insert:{insert:Bm},join:{join:km},json_mutation:{json_mutation:Km},limit:{limit:Qm},lock:{lock:Lm},offset:{offset:Wm},on_duplicate:{on_duplicate:jm},order_by:{order_by:Fm},raw:{raw:Um},returning:{returning:Vm},schema:{check_constraint_info:Jm,foreign_key_info:Hm,get_column_listing:zm,get_tables:Gm,has_check_constraint:Ym,has_column:Zm,has_index:Xm,has_primary_key:ep,has_table:tp,index_info:rp,primary_key_info:np,table_info:op},select:{select:sp,select_json:ip},sqlfunc:{sqlfunc:ap},truncate:{truncate:lp},union:{union:up},update:{update:dp},where:{where:cp,where_group:mp,where_json:pp,where_subquery:fp},window:{window:yp},with:{with:hp}},sqlite:{alter_table:{add_column:gp,add_constraint:bp,alter_column_type:Tp,alter_table:wp,drop_column:Sp,drop_constraint:Np,drop_default:qp,drop_not_null:Cp,drop_primary_key:Rp,rename_column:_p,rename_table:Mp,set_default:xp,set_not_null:Op,set_table_options:Dp},column:{column_type:Ap},comment:{comment:$p},constraint:{after:vp,constraint:Ip},create_table:{create_table:Pp},delete:{delete:Ep},distinct:{distinct:Bp,distinct_on:kp},drop_table:{drop_table:Kp},extension:{create_extension:Qp},from:{from:Lp},group_by:{group_by:Wp},having:{having:jp},index_op:{create_index:Fp,drop_index:Up},insert:{insert:Vp},join:{join:Jp},json_mutation:{json_mutation:Hp},limit:{limit:zp},lock:{lock:Gp},offset:{offset:Yp},on_duplicate:{on_duplicate:Zp},order_by:{order_by:Xp},raw:{raw:ef},returning:{returning:tf},schema:{check_constraint_info:rf,foreign_key_info:nf,get_column_listing:of,get_tables:sf,has_check_constraint:af,has_column:lf,has_index:uf,has_primary_key:df,has_table:cf,index_info:mf,primary_key_info:pf,table_info:ff},select:{select:yf,select_json:hf},sqlfunc:{sqlfunc:gf},truncate:{truncate:bf},union:{union:Tf},update:{update:wf},where:{where:Sf,where_group:Nf,where_json:qf,where_subquery:Cf},window:{window:Rf},with:{with:_f}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let n=t.find(R=>!!R&&R.folder==="distinctOn"),o=!n&&t.find(R=>!!R&&R.folder==="distinct"),s=t.filter(R=>!!R&&R.folder==="comment"&&R.isHint).map(R=>this.renderNode(R)).filter(R=>R.length>0).join(" "),a=this.dbType==="mssql"?t.find(R=>!!R&&R.folder==="lock")??null:null,l=a?this.getMssqlTableHints(a):"",u=t.filter(R=>R!==null&&R.folder!=="distinct"&&R.folder!=="distinctOn"&&!(R.folder==="comment"&&R.isHint)),d=u.some(R=>R.folder==="offset"),c=u.some(R=>R.folder==="order_by"),m=u.find(R=>R.folder==="limit"),p=u.find(R=>R.folder==="offset"),h=this.dbType==="mssql"&&m&&!d&&!c,f=this.dbType==="mssql"&&!h&&(m||p),T=[],w=[],q=null;h&&m&&w.push(m.limit);for(let R=0;R<u.length;R++){let $=u[R];if(h&&$.folder==="limit"||f&&($.folder==="limit"||$.folder==="offset"))continue;$.currParamIndex=e+w.length;let A=Kl[this.mapCommonDbType(this.dbType)][$.folder][$.file];if(!A)throw new Error(`Interpreter not found for ${this.dbType} ${$.keyword}`);A.model=this.model,A.dbType=this.dbType;let O=A.toSql($);if(!O.sql||!O.sql.trim().length)continue;let K=u[R+1],v=!K||K.keyword!==$.keyword?"":K.chainsWith;if($.folder==="lock"||$.folder==="on_duplicate"||$.folder==="returning"||$.folder==="schema"||$.folder==="comment"){T.push(`${O.sql}${v}`),w.push(...O.bindings),q=$.keyword;continue}if(q!==$.keyword||$.canKeywordBeSeenMultipleTimes){if(r)T.push(`${O.sql}${v}`);else {let ne=$.keyword;if($.folder==="with"&&this.dbType!=="mssql"){let _e=R,Me=false;for(;_e<u.length&&u[_e].keyword===$.keyword;){let uu=u[_e];if(uu.folder==="with"&&uu.clause==="recursive"){Me=true;break}_e++;}Me&&(ne=`${ne} recursive`);}let Ye=s?`${s} `:"";if(ne==="select"){let _e=h?`top (@${e}) `:"";if(n){let Me=Array.isArray(n.columns)?n.columns.join(", "):"";T.push(`select ${_e}${Ye}distinct on (${Me}) ${O.sql}${v}`);}else o?T.push(`select ${_e}${Ye}distinct ${O.sql}${v}`):T.push(`select ${_e}${Ye}${O.sql}${v}`);}else ne==="from"&&l?T.push(`${ne} ${O.sql}${l}${v}`):T.push(`${ne} ${O.sql}${v}`);}q=$.keyword;}else T.push(`${O.sql}${v}`);w.push(...O.bindings);}if(f){c||T.push("order by (select null)");let R=p?.offset??0;w.push(R);let A=`offset @${e+w.length-1} rows`;if(m){w.push(m.limit);let O=e+w.length-1;A+=` fetch next @${O} rows only`;}T.push(A);}return {sql:T.join(" "),bindings:w}}renderNode(t){let e=Kl[this.mapCommonDbType(this.dbType)][t.folder][t.file];if(!e)throw new Error(`Interpreter not found for ${this.dbType} ${t.keyword}`);return e.model=this.model,e.dbType=this.dbType,e.toSql(t).sql}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 Tr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var wr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Sr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Nr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var qr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Cr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_table";this.table=e;}};var Rr=class extends N{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_column";this.table=e,this.column=r;}};var _r=class extends N{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_index";this.table=e,this.index=r;}};var Mr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_primary_key";this.table=e;}};var xr=class extends N{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_check_constraint";this.table=e,this.constraint=r;}};var Or=class extends N{constructor(){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="get_tables";}};var Dr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="get_column_listing";this.table=e;}};var Ar=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var we=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var wt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var $r=class extends N{constructor(e,r,n={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=n;}};var fe=class extends N{constructor(e,r=[],n=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=n;}};var vr=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var Se=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var Qt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Ir=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 Pr=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 Er=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 Br=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var Nt=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 V=class extends N{constructor(e,r={},n=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=n;}};var kr=class extends N{constructor(e,r=[],n=[],o=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=n,this.ifNotExists=o,s&&Object.assign(this,s);}};var Kr=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 Qr=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 Lr=class extends N{constructor(e,r,n,o=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=n,this.unique=o;}};var Wr=class extends N{constructor(e,r,n){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=n??false;}};var qt=class extends N{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};function Ch(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 jr=Symbol("columns"),Ct=Symbol("primaryKey"),Ql=Symbol("relations"),Mf=Symbol("indexes"),xf=Symbol("uniques"),Of=Symbol("checks"),Ll=i=>`${Ch(i)}_id`,Wl=(i,t)=>`idx_${i}_${t}`,Ne=(i,t)=>`uq_${i}_${t}`,Z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,qe=(i,t)=>`pk_${i}_${t}`;var k=class extends N{constructor(e,r,n={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=n.length,this.precision=n.precision,this.scale=n.scale,this.enumValues=n.enumValues,this.withTimezone=n.withTimezone,this.autoIncrement=n.autoIncrement,this.autoCreate=n.autoCreate,this.autoUpdate=n.autoUpdate,this.collate=n.collate,this.isRawValue=n.isRawValue??false,this.unsigned=n.unsigned,this.zerofill=n.zerofill;}};var Lt=class extends N{constructor(e,r=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="comment";this.file="comment";this.value=e,this.isHint=r;}};var Xe=class extends N{constructor(e,r=false,n=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=n;}};var Fr=class extends N{constructor(e,r=[],n=[]){super("window");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="window";this.file="window";this.fn=e,this.partitionBy=r,this.orderBy=n;}};function Df(i){return i?Array.isArray(i)?i:[i]:[]}function Af(i){return i?(Array.isArray(i)?i:[i]).map(e=>typeof e=="string"?{column:e}:e):[]}var Ie=class extends N{constructor(e,r=false,n="union"){super(r?`${n} all`:n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r,this.type=n;}};var et=class extends N{constructor(e,r,n){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=n,this.clause=e;}};var Fe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Ur=class extends N{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var Vr=class extends Fe{constructor(t,e,r,n,o=[],s="create_table"){super(e),this.columnNode=r,this.tableName=n,this.namedConstraints=o,this.context=s,this.sqlType=t;}primaryKey(t){let e=qe(this.tableName,C(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new V("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new V("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){this.columnNode.isForeignKey=true;let[r,n]=t.split("."),o=n.split(","),s=e?.constraintName??Z(this.tableName??"",C(this.columnNode.column),o[0]);return this.context==="alter_table"?(this.nodes.push(new V("foreign_key",{columns:[C(this.columnNode.column)],references:{table:r,columns:o},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new V("foreign_key",{columns:[C(this.columnNode.column)],references:{table:r,columns:o},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 V("not_null",{columns:[C(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new V("null",{columns:[C(this.columnNode.column)]})),this}default(t){let e;return t instanceof x||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 V("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new V("unique",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??Ne(this.tableName??"",C(this.columnNode.column))})),this):(this.namedConstraints.push(new V("unique",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName||Ne(this.tableName??"",C(this.columnNode.column))})),this)}check(t,e){let r=C(this.columnNode.column),n=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new V("check",{columns:[r],checkExpression:t,constraintName:n})),this):(this.namedConstraints.push(new V("check",{columns:[r],checkExpression:t,constraintName:n})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new Ur(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.isInlineSqlitePrimaryKey()?this:(this.nodes.push(new V("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this)}isInlineSqlitePrimaryKey(){let t=(this.columnNode.dataType??"").toLowerCase();return t==="bigincrement"?true:(t==="integer"||t==="bigint"||t==="int")&&!!this.columnNode.autoIncrement}};var tt=class extends Fe{constructor(e,r,n,o){super(r);this.context="create_table";this.tableName=n,this.namedConstraints=[],this.context=o??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new Vr(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new x(e)}char(e,r=1){let n=new k(e,"char",{length:r});return this.build(n)}varchar(e,r=255){let n=new k(e,"varchar",{length:r});return this.build(n)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let n=new k(e,r);return this.build(n)}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 k(e,"uuid");return this.build(r)}ulid(e){let r=new k(e,"ulid");return this.build(r)}integer(e,r=255){let n=new k(e,"integer",{length:r});return this.build(n)}tinyint(e,r=255){let n=new k(e,"tinyint",{length:r});return this.build(n)}smallint(e,r=255){let n=new k(e,"smallint",{length:r});return this.build(n)}mediumint(e,r=255){let n=new k(e,"mediumint",{length:r});return this.build(n)}biginteger(e,r=255){let n=new k(e,"bigint",{length:r});return this.build(n)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let n=new k(e,"float",{precision:r});return this.build(n)}double(e,r=10){let n=new k(e,"double",{precision:r});return this.build(n)}real(e,r=10){let n=new k(e,"real",{precision:r});return this.build(n)}decimal(e,r=10,n=2){let o=new k(e,"decimal",{precision:r,scale:n});return this.build(o)}numeric(e,r=10,n=2){let o=new k(e,"numeric",{precision:r,scale:n});return this.build(o)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let n=new k(e,"date",{precision:r});return this.build(n)}time(e,r){let n=new k(e,"time",{precision:r});return this.build(n)}year(e){let r=new k(e,"year");return this.build(r)}datetime(e,r){let n=new k(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(n)}timestamp(e,r){let n=new k(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(n)}boolean(e){let r=new k(e,"boolean");return this.build(r)}binary(e){let r=new k(e,"binary");return this.build(r)}varbinary(e,r=255){let n=new k(e,"varbinary",{length:r});return this.build(n)}blob(e){let r=new k(e,"blob");return this.build(r)}tinyblob(e){let r=new k(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new k(e,"mediumblob");return this.build(r)}longblob(e){let r=new k(e,"longblob");return this.build(r)}json(e){let r=new k(e,"json");return this.build(r)}jsonb(e){let r=new k(e,"jsonb");return this.build(r)}enum(e,r){let n=new k(e,"enum",{enumValues:r});return this.build(n)}custom(e,r,n){let o=new k(e,r,{length:n});return this.build(o)}rawColumn(e){let r=new k(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new k(e,"geometry");return this.build(r)}point(e){let r=new k(e,"point");return this.build(r)}linestring(e){let r=new k(e,"linestring");return this.build(r)}polygon(e){let r=new k(e,"polygon");return this.build(r)}multiPoint(e){let r=new k(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Jr=class extends Fe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new x(t)}addColumn(t){let e=[],r=new tt(this.sqlType,e,this.table,"alter_table"),n=t(r);if(!e.length)return;let o=r.getNamedConstraints(),s=e.filter(c=>c.folder==="column");if(e=e.concat(o),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=n.getNodes().filter(c=>{let m=c;return m.constraintType==="not_null"||m.constraintType==="null"||m.constraintType==="default"}),u=new Ar(a);u.inlineConstraints=l,this.nodes.push(u),n.getNodes().filter(c=>{let m=c;return m.constraintType==="unique"||m.constraintType==="foreign_key"||m.constraintType==="primary_key"}).forEach(c=>{this.nodes.push(new we(c));});}alterColumn(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new tt(this.sqlType,e,this.table,"alter_table"),n=t(r);if(!e.length)return;let o=e.filter(p=>p.folder==="column");if(o.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=o[0],a=C(s.column),l=n.getNodes().find(p=>p.constraintType==="null"),d=n.getNodes().find(p=>p.constraintType==="not_null")||l,c=n.getNodes().find(p=>p.constraintType==="default"),m={};d&&(m.nullable=d.constraintType==="null"),c&&(c.defaultValue===void 0||c.defaultValue===null||c.defaultValue==="NULL"?m.dropDefault=true:m.default=c.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(m.collate=s.collate),this.nodes.push(new $r(C(a),s,m)),d&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(d.constraintType==="not_null"?this.nodes.push(new Br(C(a))):d.constraintType==="null"&&this.nodes.push(new Ir(C(a)))),c&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(c.defaultValue===void 0||c.defaultValue===null||c.defaultValue==="NULL"?this.nodes.push(new Qt(C(a))):this.nodes.push(new Er(C(a),c.defaultValue))),n.getNodes().forEach(p=>{let h=p;switch(h.constraintType){case "primary_key":this.addPrimaryKey(C(a));break;case "unique":this.unique(C(a),{constraintName:h.constraintName});break;case "foreign_key":this.foreignKey(C(a),h.references?.table??"",C(h.references?.columns?.[0]??""),{constraintName:h.constraintName,onDelete:h.onDelete,onUpdate:h.onUpdate});break}});}dropColumn(t){this.nodes.push(new vr(t));}renameColumn(t,e){this.nodes.push(new Pr(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Qt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new wt([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new we(new V(...t)));}foreignKey(t,e,r,n){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new we(new V("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:n?.constraintName??Z(this.table,t,r),onDelete:n?.onDelete,onUpdate:n?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new we(new V("unique",{columns:[t],constraintName:e?.constraintName??Ne(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new S("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 Se(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new S("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??Ne(this.table,t);this.nodes.push(new Se(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Se(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new S("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",n=this.sqlType==="mssql";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new Nt(t)):r?this.nodes.push(new Nt(t)):n&&this.nodes.push(new Nt(t)),this)}};var ce=class{constructor(t){if(this.sqlType=t||E.DB_TYPE,!this.sqlType)throw new S("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new x(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!ae.existsSync(t))throw new S("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=yt.basename(t),r=yt.extname(e);if(r!==".sql"&&r!==".txt")throw new S("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let o=ae.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of o)this.rawQuery(s);}createTable(t,e,r){let n=new tt(this.sqlType,[],t);e(n);let o=n.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?n.getMysqlOptions()||{}:{}},l=new kr(t,o,n.getNamedConstraints(),r?.ifNotExists,a),u=s.parse([l]).sql,d=u.startsWith("create table")?u:`create table ${u}`;this.rawQuery(d),this.generateAutoUpdateTriggers(t,o);}alterTable(t,e){let r=[],n=new Jr(t,r,this.sqlType);if(e(n),!r.length)return;let o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"}),s=[],a=()=>{if(!s.length)return;let u=new fe(t,s),d=o.parse([u]).sql;if(!d||!d.trim())return;let c=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(c),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 Kr(t,e),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}renameTable(t,e){let r=new fe(t,[new gt(e)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}truncateTable(t){let e=new qt(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 n=r.constraintName||Wl(t,e.join("_")),o=new Lr(t,e,n),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([o]).sql);}dropIndex(t,e){let r=new Wr(t,e),n=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}addPrimaryKey(t,e){let r=new fe(t,[new wt(e)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}addUnique(t,e,r){let n=Array.isArray(e)?e:[e],o=r?.constraintName??Ne(t,n.join("_")),s=new V("unique",{columns:n,constraintName:o}),a=new fe(t,[new we(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let n=Z(t,e,r),o=new Se(n),s=new fe(t,[o]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let n=Array.isArray(e)?Ne(t,e.join("_")):Ne(t,e),o=r?.constraintName??n,s=new Se(o),a=new fe(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new St,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new V(...e),n=new fe(t,[new we(r)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([n]).sql);}dropConstraint(t,e){let r=new Se(e),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}addCheck(t,e,r){let n=r?.constraintName??`chk_${t}_custom`.substring(0,63),o=new V("check",{checkExpression:e,constraintName:n}),s=new fe(t,[new we(o)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new Se(e),n=new fe(t,[r]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([n]).sql);}createExtension(t,e=true){let r=new Qr(t,e),n=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(n=>n.folder==="column"&&n.autoUpdate===true).map(n=>C(n.column));for(let n of r){let o=this.getAutoUpdateTriggerSql(t,n);for(let s of o)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`];default:return []}}generateAstInstance(t){return new b(t,this.sqlType)}};var Hr,If,Wt=class{constructor(t,e){fu(this,Hr);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new ce(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=yu(this,Hr,If).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(`;
259
- `)}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"}async hasTable(t){return this.dataSource.hasTable(t)}async hasColumn(t,e){return this.dataSource.hasColumn(t,e)}async hasColumns(t,...e){return this.dataSource.hasColumns(t,...e)}async hasIndex(t,e){return this.dataSource.hasIndex(t,e)}async hasPrimaryKey(t){return this.dataSource.hasPrimaryKey(t)}async hasUnique(t,e){return this.dataSource.hasUnique(t,e)}async hasForeignKey(t,e){return this.dataSource.hasForeignKey(t,e)}async hasCheckConstraint(t,e){return this.dataSource.hasCheckConstraint(t,e)}async getTables(){return this.dataSource.getTables()}async getColumnListing(t){return this.dataSource.getColumnListing(t)}dropTableIfExists(t){return this.schema.dropTable(t,true),this}async dropIndexIfExists(t,e){if(await this.dataSource.hasIndex(e,t)){let n=new ce(this.dataSource.getDbType());n.dropIndex(t,e);let o=n.queryStatements[0];o&&await this.dataSource.rawQuery(o);}}renameColumn(t,e,r){return this.schema.alterTable(t,n=>{n.renameColumn(e,r);}),this}};Hr=new WeakSet,If=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 Oe=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var zr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}buildDropDependencies(t){let e=new Map,r=new Map,n=new Map;for(let o of t.relationsToDrop||[]){let s=`${o.table}.${o.relation.name}`,a=[];if(o.relation.referencedTable&&a.push(`table.${o.relation.referencedTable}`),o.relation.referencedColumns)for(let l of o.relation.referencedColumns)a.push(`column.${o.relation.referencedTable}.${l}`);e.set(s,a);}for(let o of t.tablesToDrop||[]){let s=`table.${o.table}`,a=[];for(let l of this.models){let u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===o.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let o of t.columnsToDrop||[]){let s=`column.${o.table}.${o.column}`,a=[],l=this.models.find(u=>u.table===o.table);if(l){let u=l.getColumns().find(d=>d.databaseName===o.column);if(u){u.isPrimary&&a.push(`pk.${o.table}`);let d=l.getRelations();for(let c of d)c.columnName===u.columnName&&a.push(`fk.${o.table}.${c.constraintName}`);}}n.set(s,a);}return {foreignKeys:e,tables:r,constraints:n}}topologicalSortReverse(t,e){let r=new Set,n=new Set,o=[],s=a=>{if(n.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;n.add(a);let l=e(a);for(let u of l)s(u);n.delete(a),r.add(a),o.push(a);};for(let a of t.keys())r.has(a)||s(a);return o}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],n=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of n){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 o=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 o){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 n=[],o=this.models.find(s=>s.table===r.table);if(o){let s=o.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&n.push(`PRIMARY KEY on ${r.table}`);let a=o.getRelations();for(let l of a)l.columnName===s.columnName&&n.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,n);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let n=this.models.find(o=>o.table===r.table);n&&n.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,n=>{n.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 Fl=i=>String(i??"").replace(/::[a-z_ ]+$/i,"").replace(/[()\s]/g,"").toLowerCase(),Rh=/^(current[ _]?timestamp\d*|now\d*|getdate\d*|localtimestamp\d*|localtime\d*)$/,_h={postgres:i=>i.includes("nextval"),cockroachdb:i=>i.includes("unique_rowid")},Mh={postgres:["gen_random_uuid"],cockroachdb:["gen_random_uuid"],mysql:["uuid"],mariadb:["uuid"],mssql:["newid"],sqlite:["lower(hex(randomblob(16)))"]},Ef=(i,t)=>(Mh[i]??[]).includes(Fl(t)),Rt=(i,t)=>!!i.autoCreate&&Rh.test(Fl(t)),_t=(i,t,e)=>{if(t.type!=="increment"&&t.type!=="bigIncrement")return false;let r=_h[i];return r?r(Fl(e)):false};var Gr=class Gr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new zr(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,n=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),o=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...n].filter(l=>o.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 n=this.sql.schema().createTable(r.table,o=>{for(let s of r.columns){if(Array.isArray(s.type)){o.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,o,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:[n]});}for(let r of t.columnsToAdd){let n=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:n});}return e}generateConstraintCreationOperations(t){let e=[];for(let n of t.uniquesToDrop||[]){let o=this.sql.schema().alterTable(n.table,s=>{s.dropConstraint(n.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:o});}let r=new Set((t.uniquesToDrop||[]).map(n=>n.name));for(let n of t.indexesToDrop){if(r.has(n.index))continue;let o=new ce(this.sql.getDbType());o.dropIndex(n.index,n.table);let s=o.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[s]});}for(let n of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===n.table)?.getColumns().find(u=>u.columnName===n.columns[0])?.primaryKeyConstraintName||qe(n.table,n.columns[0]),l=this.sql.schema().alterTable(n.table,u=>{let d=a||qe(n.table,n.columns[0]);u.addConstraint("primary_key",{columns:[n.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:a,data:n,dependencies:[`table.${n.table}`],sqlStatements:l});}for(let n of t.relationsToAdd){if(n.relation.type==="manyToMany")continue;let o=this.generateAddRelationViaAlter(n),s=this.computeFkConstraintName(n);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:s,data:n,dependencies:this.getForeignKeyDependencies(n),sqlStatements:o});}for(let n of t.uniquesToAdd||[]){let o=this.models.find(l=>l.table===n.table),s=(n.columns||[]).map(l=>o?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(n.table,l=>{l.addConstraint("unique",{columns:s,constraintName:n.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name||"mandatory",data:n,dependencies:[`table.${n.table}`],sqlStatements:a});}for(let n of t.indexesToAdd){let o=this.generateCreateIndexSql(n);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[o]});}for(let n of t.checksToDrop||[]){let o=new ce(this.sql.getDbType());o.dropCheck(n.table,n.name);let s=o.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}for(let n of t.checksToAdd||[]){let o=new ce(this.sql.getDbType());o.addCheck(n.table,n.expression,{constraintName:n.name});let s=o.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=C(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=C(t.relation.manyToManyOptions.throughModel));let o=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=o.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=o.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 n=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:n});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let n=t.relation.model();e.push(`table.${n.table}`);let o=n.primaryKey||"id",s=n.getColumns().find(a=>a.columnName===o);s&&e.push(`column.${n.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let n=C(t.relation.manyToManyOptions.throughModel);e.push(`table.${n}`);}e.push(`table.${t.table}`);let r=this.models.find(n=>n.table===t.table);if(r){let n=r.getColumns().find(o=>o.columnName===t.relation.columnName||o.databaseName===t.relation.columnName);n&&e.push(`column.${t.table}.${n.databaseName}`);}return e}applyNullableConstraint(t,e){return e===false?t.notNullable():e===true||this.sql.getDbType()==="mariadb"?t.nullable():t}executeBuilderMethod(t,e,r,n,o=true){let s;if(Array.isArray(r.type))s=e.enum(n[0],r.type);else if(typeof r.type=="string"&&Gr.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...n);else if(typeof r.type=="string")s=e.custom(n[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return o&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||qe(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),this.applyNullableConstraint(s,r.constraints?.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(n=>{let o=this.executeBuilderMethod(t.table,n,t.column,e,false);return t.column.constraints?.default!==void 0&&o.default(t.column.constraints.default),this.applyNullableConstraint(o,t.column.constraints?.nullable),o});}).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,n=>{n.alterColumn(o=>{let s=this.executeBuilderMethod(t.table,o,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&!Rt(t.modelColumn,t.dbColumns.defaultValue)&&!_t(this.sql.getDbType(),t.modelColumn,t.dbColumns.defaultValue)&&s.default(null),this.applyNullableConstraint(s,t.modelColumn.constraints?.nullable),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),n=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),o=new ce(this.sql.getDbType());return o.createIndex(t.table,n,{constraintName:t.index}),o.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=C(t.relation.manyToManyOptions.throughModel),r=C(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let n=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,o=C(r);if(t.relation.type==="belongsTo"){let m=t.relation.model(),p=m.primaryKey,f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=H(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.model();if(typeof o=="string"&&o){let p=m.getColumns(),h=p.find(f=>f.columnName===o);if(h)o=h.databaseName;else {let f=m.primaryKey||"id",T=p.find(w=>w.columnName===f);if(T)o=T.databaseName;else {let w=m?.databaseCaseConvention||"preserve";o=H(o||f,w);}}}else {let p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=H(p,T);}}}let s=this.models.find(m=>m.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(m=>m.columnName===l);if(u)l=u.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=H(l,m);}if(t.relation.type==="belongsTo"){let m=a.find(p=>p.columnName===t.relation.foreignKey);if(m)l=m.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=H(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.manyToManyOptions.leftForeignKey,p=C(m),h=a.find(f=>f.columnName===p);if(h)l=h.databaseName;else {let f=s?.databaseCaseConvention||"preserve";l=H(p,f);}}let d=t.relation.onDelete?.toLowerCase(),c=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,m=>{let p=n||Z(t.table,l,e);m.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[o]},constraintName:p,onDelete:d,onUpdate:c});}).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," "))}))}};Gr.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 jt=Gr;var Zr=class Zr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],n=null,o={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==n&&(n=s.phase,e.length>0&&e.push(""),e.push(`// ${o[n]}`));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 o of e.columns){let s=this.generateColumnCode(e.table,o,true);r.push(` ${s}`);}r.push("});");let n=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:n}}generateAddColumnCode(t){let{table:e,column:r}=t.data,n=this.generateColumnCode(e,r,false),o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:o,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:n}=t.data,o=this.generateColumnCodeForModify(e,r,n),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(n.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],o=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:n,down:o}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u),s=o.length===1?this.quote(o[0]):`[${o.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)});`],n=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:n}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:n,referencedColumn:o,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(", ")} }`:"",c=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(n)}, ${this.quote(o)}${d});`,"});"],m=s||Z(e.table,r,n),p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(m)});`,"});"];return {up:c,down:p}}generateDropForeignKeyCode(t){let e=t.constraint||t.data?.relation?.name;if(!e)return {up:null,down:null};let r=t.table||t.data?.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],o=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:n,down:o}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=`[${(e.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,n=t.constraint||e.name;if(!n||!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(n)});`,"});"],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(n)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:a,down:l}}let o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(n)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:o,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)} });`],n=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:n}}generateAddPrimaryKeyCode(t){let e=t.data,o=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||qe(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(o)} });`,"});"],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)});`],n=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:n}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],o=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:n,down:o}}generateColumnCode(t,e,r){let n=this.generateColumnTypeCode(e);if(!r)return n;if(e.isPrimary){let o=e.primaryKeyConstraintName||qe(t,e.columnName);n+=`.primaryKey({ constraintName: ${this.quote(o)} })`;}return e.unsigned&&(n+=".unsigned()"),e.zerofill&&(n+=".zerofill()"),e.constraints?.default!==void 0&&(n+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n+";"}generateColumnCodeForModify(t,e,r){let n=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?n+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&!Rt(e,r.defaultValue)&&!_t(this.sql.getDbType(),e,r.defaultValue)&&(n+=".default(null)"),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n}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)})`:Zr.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(m=>m.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=C(t.relation.manyToManyOptions.throughModel);let l=C(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let o=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=o.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=C(t.relation.manyToManyOptions.leftForeignKey);s=o.find(d=>d.columnName===l)?.databaseName||l;}else s=o.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName:C(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))}};Zr.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 Yr=Zr;function Oh(i){return i.replace(/\s+/g," ").trim()}function Dh(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ah(i){let t=i.split(/\s+/).filter(n=>n.length>0),e=[],r=[];for(let n of t)n==="unsigned"||n==="zerofill"?e.push(n):r.push(n);return {bareBase:r.join(" "),modifiers:e}}function $h(i,t){return t.length===0?i:`${i} ${t.join(" ")}`}function Ue(i,t){let e=Oh(t.toLowerCase()),r=Dh(e);switch(i){case "sqlite":{let n=[{test:o=>o==="increment",normalized:"integer"},{test:o=>o==="bigincrement",normalized:"integer"},{test:o=>o.includes("int"),normalized:"integer"},{test:o=>o==="string",normalized:"varchar"},{test:o=>o.includes("char"),normalized:"varchar"},{test:o=>o.includes("text"),normalized:"text"},{test:o=>o.includes("clob"),normalized:"text"},{test:o=>o.includes("date"),normalized:"text"},{test:o=>o.includes("time"),normalized:"text"},{test:o=>o.includes("timestamp"),normalized:"text"},{test:o=>o.includes("datetime"),normalized:"text"},{test:o=>o.includes("blob"),normalized:"blob"},{test:o=>o.includes("real")||o.includes("floa")||o.includes("doub"),normalized:"real"},{test:o=>o.includes("numeric"),normalized:"numeric"},{test:o=>o.includes("bool"),normalized:"integer"},{test:o=>o.includes("uuid"),normalized:"varchar"},{test:o=>o.includes("ulid"),normalized:"varchar"},{test:o=>o.includes("jsonb"),normalized:"text"},{test:o=>o.includes("json"),normalized:"text"}];for(let o of n)if(o.test(r))return o.normalized;return r}case "mysql":case "mariadb":{let{bareBase:n,modifiers:o}=Ah(r),a=new Set(["int","integer","increment","tinyint","smallint","mediumint","bigint","bigincrement","float","double","double precision","real","decimal","numeric","year","bool","boolean"]).has(n);if(n.endsWith("text")||n==="text")return "text";let l;switch(n){case "int":case "integer":case "increment":l="integer";break;case "tinyint":l="boolean";break;case "smallint":l="smallint";break;case "mediumint":l="mediumint";break;case "bigint":case "bigincrement":l="bigint";break;case "float":l="float";break;case "double":case "double precision":l="double";break;case "real":l="double";break;case "decimal":case "numeric":l="numeric";break;case "string":case "varchar":case "character varying":l="varchar";break;case "char":case "character":l="char";break;case "uuid":l="varchar";break;case "ulid":l="varchar";break;case "date":l="date";break;case "datetime":l="datetime";break;case "timestamp":l="timestamp";break;case "time":l="time";break;case "year":l="year";break;case "jsonb":case "json":l=i==="mariadb"?"text":"json";break;case "enum":l="enum";break;case "binary":l="binary";break;case "varbinary":l="varbinary";break;case "tinyblob":l="tinyblob";break;case "mediumblob":l="mediumblob";break;case "longblob":l="longblob";break;case "blob":l="blob";break;case "boolean":case "bool":l="boolean";break;default:l=n;break}return a&&o.length>0?$h(l,o):l}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}}default:return r}}var rt=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 n=await e.sql.getTableSchema(r.table),o={columns:r.getColumns().filter(f=>f?.type!==void 0&&f?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!n.columns.length){e.data.tablesToAdd.push({table:r.table,columns:o.columns});for(let w of o.indexes)n.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 T=r.getChecks?.()||[];for(let w of T)e.data.checksToAdd.push({table:r.table,name:w.name,expression:w.expression});for(let w of o.relations){if(w.type!=="belongsTo")continue;let q=C(w.constraintName);n.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 o.columns)n.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 n.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 o.indexes)n.indexes.map(T=>T.name).includes(f.name)||e.data.indexesToAdd.push({table:r.table,index:f.name});let a=r.getUniques?.()||[];for(let f of a)n.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=n.foreignKeys.map(f=>f.name);for(let f of n.indexes)f.isUnique||l.includes(f.name)||o.indexes.map(w=>w.name).includes(f.name)||e.data.indexesToDrop.push({table:r.table,index:f.name});for(let f of n.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)n.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)),c=o.columns.filter(f=>Array.isArray(f.type)),m=new Set(c.map(f=>f.databaseName||f.columnName));for(let f of n.checkConstraints)if(!d.has(f.name)){let T=[...m].find(w=>{let q=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),D=new RegExp(`[\\["\\[]?${q}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i"),R=new RegExp(`[\\("\\[]?${q}[\\)"\\]]?(?:::text)?\\s*=\\s*ANY\\s*\\(`,"i");return D.test(f.expression)||R.test(f.expression)});if(T){let w=c.find(D=>(D.databaseName||D.columnName)===T),q=n.columns.find(D=>D.name===T);if(w&&q?.enumValues&&Array.isArray(w.type)){let D=[...w.type].sort(),R=[...q.enumValues].sort();if(!(D.length===R.length&&D.every((A,O)=>A===R[O]))){e.data.checksToDrop.push({table:r.table,name:f.name});let A=e.sql.getDbType(),O=A==="mssql"?"[":'"',K=A==="mssql"?"]":'"',le=w.type.map(v=>`'${v.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:f.name,expression:`${O}${T}${K} IN (${le})`});}}}else e.data.checksToDrop.push({table:r.table,name:f.name});}for(let f of o.columns){let T=n.columns.find(D=>D.name===f.databaseName||D.name===f.columnName);if(!T)continue;let w=!e.areColumnsEqual(T,f,n.indexes),q=e.getDefaultChange({table:r.table,dbColumns:T,modelColumn:f});(w||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:T,modelColumn:f});}for(let f of o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;if(f.type==="manyToMany"&&f.manyToManyOptions){let q=C(f.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:C(f.manyToManyOptions.leftForeignKey),foreignKey:f.manyToManyOptions.leftForeignKey,constraintName:f.constraintName?C(f.constraintName):Z(q,C(f.manyToManyOptions.leftForeignKey||Ll(r.table)),r.table),onDelete:f.onDelete,onUpdate:f.onUpdate},onDelete:f.onDelete,onUpdate:f.onUpdate});continue}let T=C(f.constraintName);if(T&&n.foreignKeys.some(q=>q.name===T))continue;n.foreignKeys.find(q=>e.relationMatchesDbRelation(r,f,q))||e.data.relationsToAdd.push({table:r.table,relation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let p=new Set(o.relations.filter(f=>f.type==="belongsTo").map(f=>{let T=C(f.foreignKey)||f.columnName,q=r.getColumns().find(D=>D.columnName===T)?.databaseName||T;return C(f.constraintName)||Z(r.table,q,f.model().table)}));for(let f of n.foreignKeys){if(f.name&&p.has(f.name))continue;o.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 o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;let T=n.foreignKeys.find(w=>e.relationMatchesDbRelation(r,f,w));T&&!e.areRelationsEqual(T,f)&&e.data.relationsToModify.push({table:r.table,dbRelation:T,modelRelation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let h=r.primaryKey;if(h&&!n.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[h]}),n.primaryKey&&!h&&e.data.primaryKeysToDrop.push({table:r.table,columns:n.primaryKey.columns,name:n.primaryKey.name}),h&&n.primaryKey){let f=r.getColumns().find(T=>T.columnName===h);f&&!e.arePrimaryKeysEqual(n.primaryKey,f)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:n.primaryKey,modelPrimaryKey:h});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let n=r.trim();return n?!this.emptyStatements.some(o=>o.test(n)):false})}getCodeStatements(){let e=new jt(this.sql).generateOperations(this.data);return new Yr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new jt(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),n={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let o of r)n[o.phase].push(...o.sqlStatements);return n}areColumnsEqual(t,e,r=[]){let n=t.name===e.databaseName,o=this.sql.getDbType(),s=Ue(o,t.dataType),a=typeof e.type=="string"?Ue(o,e.type):void 0,l=s.split(" ").filter(d=>d!=="unsigned"&&d!=="zerofill").join(" ");if(a&&n&&(n=l===a),Array.isArray(e.type)&&(o==="mysql"||o==="mariadb")){let d=[...e.type].sort(),c=t.enumValues?[...t.enumValues].sort():null;c&&n&&(n=d.length===c.length&&d.every((m,p)=>m===c[p]));}e.length!=null&&t.length!=null&&n&&(n=t.length===e.length);let u=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(o==="postgres"||o==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&n&&(n=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,c=t.isNullable;n=n&&d===c;}if(o==="mysql"||o==="mariadb"){if(e.unsigned!==void 0){let d=e.unsigned??false,c=t.unsigned??false;n&&(n=d===c);}if(e.zerofill!==void 0){let d=e.zerofill??false,c=t.zerofill??false;n&&(n=d===c);}}if(e.stringMode!==void 0){let d=e.stringMode??false,c=t.stringMode??false;n&&(n=d===c);}return n}areRelationsEqual(t,e){let r=C(e.constraintName),n=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",c=u.getColumns().find(h=>h.columnName===d),m=u.table,p=c?.databaseName||d;n=n&&t.referencedTable===m&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=C(e.manyToManyOptions.throughModel);n=n&&t.referencedTable===u;}let o=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&n&&(n=o===a),l&&n&&(n=s===l),n}relationMatchesDbRelation(t,e,r){let n,o=e;if(o&&o.model){if(typeof o.model=="function"&&o.model.table)n=o.model;else if(typeof o.model=="function")try{let f=o.model();f&&f.table&&(n=f);}catch{}}if(!n)return false;let s=e.type==="belongsTo"?n.table:e.type==="manyToMany"&&e.manyToManyOptions?C(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=C(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),d=(o.type||"belongsTo")==="belongsTo"?C(o.foreignKey):o.columnName,c=l.find(f=>f.columnName===d);c&&(d=c.databaseName);let m=n.primaryKey||"id",h=n.getColumns().find(f=>f.columnName===m)?.databaseName||m;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let n=t.columns[0]===e.databaseName,o=this.sql.getDbType();if(["mysql","mariadb"].includes(o))return n;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return n&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Ue(e,t.dbColumns.dataType),n=typeof t.modelColumn.type=="string"?Ue(e,t.modelColumn.type):void 0;if(n&&r!==n||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"&&(n==="timestamp"||n==="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;if(s&&!a)return "set";if(!s&&a){let l=t.dbColumns.defaultValue;return _t(e,t.modelColumn,l)||Rt(t.modelColumn,l)||t.modelColumn.type==="uuid"&&Ef(e,l)?false:"drop"}if(s&&a){let l=String(t.dbColumns.defaultValue),u=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,l),c=this.normalizeDefaultValue(e,n||r,u);return d!==c?"set":false}return false}normalizeDefaultValue(t,e,r){let n=String(r).trim();if(!n)return n;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=n.match(/^'(.*)'$/s);if(s&&(n=s[1]),n==="{}"||n==="")return "{}";let a=JSON.parse(n);return JSON.stringify(a)}catch{}n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),/^true$/i.test(n)?"true":/^false$/i.test(n)?"false":/^null$/i.test(n)?"null":(n)}if(t==="mysql"||t==="mariadb"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);if(o&&(n=o[1]),/^current_timestamp(?:\(\d+\))?$/i.test(n))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(n))return "true";if(/^0$/.test(n))return "false"}return n}if(t==="sqlite"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),n.toLowerCase()}return n}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let n of r){if(n.type!=="manyToMany"||!n.manyToManyOptions||n.manyToManyOptions.wasModelProvided)continue;let o=C(n.manyToManyOptions.throughModel);if(t.has(o))continue;t.add(o);let s=this.models.find(v=>v.table===n?.manyToManyOptions?.primaryModel),a=n.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find(v=>v.columnName===l),c=a.getColumns().find(v=>v.columnName===u);if(!d||!c)continue;let m=C(n.manyToManyOptions.leftForeignKey)||l,p=C(n.manyToManyOptions.rightForeignKey)||u,h=await this.sql.getTableSchema(o);if(!h.columns.length){this.data.tablesToAdd.push({table:o,columns:[this.clonePkAsColumn(d,m),this.clonePkAsColumn(c,p)]}),this.pushM2mFkRelations({throughTable:o,leftModel:s,rightModel:a,leftFkName:m,rightFkName:p,onDelete:n.onDelete,onUpdate:n.onUpdate,constraintName:void 0});continue}let f=this.clonePkAsColumn(d,m),T=this.clonePkAsColumn(c,p),w=h.columns.find(v=>v.name===m),q=h.columns.find(v=>v.name===p),D=w?this.areColumnsEqual(w,f,h.indexes):false,R=q?this.areColumnsEqual(q,T,h.indexes):false;for(let v of h.foreignKeys){let ne=v.referencedTable===s.table,Ye=v.referencedTable===a.table;if(!ne&&!Ye)continue;let _e=ne?m:p,Me=v.columns[0];Me&&Me!==_e&&(this.data.relationsToDrop.push({table:o,relation:v}),Me!==m&&Me!==p&&this.data.columnsToDrop.push({table:o,column:Me}));}let $={};D||($[f.databaseName]=f),R||($[T.databaseName]=$[T.databaseName]||T);for(let v of Object.keys($))this.data.columnsToAdd.push({table:o,column:$[v]});let A=this.buildBelongsToRelation(o,()=>s,m,l,void 0,n.onDelete,n.onUpdate),O=this.buildBelongsToRelation(o,n.model,p,u,void 0,n.onDelete,n.onUpdate),K=h.foreignKeys.find(v=>v.referencedTable===s.table&&v.columns.length===1&&v.columns[0]===m),le=h.foreignKeys.find(v=>v.referencedTable===a.table&&v.columns.length===1&&v.columns[0]===p);if(!K){let v=h.foreignKeys.find(ne=>ne.referencedTable===s.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(A);}if(!le){let v=h.foreignKeys.find(ne=>ne.referencedTable===a.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(O);}}}}async removeFkChurnByName(){let t=new Set;for(let n of this.data.relationsToAdd)t.add(n.table);for(let n of this.data.relationsToDrop)t.add(n.table);let e=new Map;for(let n of t){let o=await this.sql.getTableSchema(n),s=new Set((o.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(n,s);}let r=new Map;for(let n of this.models){let o=n.getRelations(),s=new Set;for(let a of o){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=n.getColumns().find(m=>m.columnName===l)?.databaseName||l,c=C(a.constraintName)||Z(n.table,d,a.model().table);s.add(c);}r.set(n.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async n=>{let o=await this.sql.getTableSchema(n.table),s=this.models.find(f=>f.table===n.table),a=s?.getColumns()||[],l=n.relation.columnName;n.relation.type==="belongsTo"?l=a.find(T=>T.columnName===n.relation.foreignKey)?.databaseName||n.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let u=n.table,d=n.relation.foreignKey;if(n.relation.type==="belongsTo"){let f=n.relation.model();u=f.table;let T=f.primaryKey||"id";d=f.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let c=new Set([l,n.relation.columnName].filter(Boolean)),m=o.foreignKeys.some(f=>{if(f.columns.length!==1||f.referencedColumns.length!==1)return false;let T=c.has(f.columns[0]),w=f.referencedTable===u,q=f.referencedColumns[0]===d;return T&&w&&q}),p=C(n.relation.constraintName)||Z(n.table,l,u),h=e.get(n.table)||new Set;if(m||p&&h.has(p))return null;if(n.relation.type==="manyToMany"&&n.relation.manyToManyOptions){let f=C(n.relation.manyToManyOptions.throughModel),T=C(n.relation.manyToManyOptions.leftForeignKey),w=C(n.relation.manyToManyOptions.rightForeignKey),q=n.table===f&&n.relation.columnName===T&&n.relation.model().table===s?.table,D=n.table===f&&n.relation.columnName===w&&n.relation.model().table!==s?.table,R=await this.sql.getTableSchema(f),$=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===T&&O.referencedTable===(s?.table||"")),A=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===w&&O.referencedTable===n.relation.model().table);if(q&&$||D&&A)return null}return n})).then(n=>n.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async n=>{let o=this.models.find(u=>u.table===n.table);if(!o)return n;let s=o.getRelations(),a=o.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let c=a.find(T=>T.columnName===u.foreignKey)?.databaseName||u.foreignKey,m=u.model(),p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p)?.databaseName||p;return n.relation.columns.length===1&&n.relation.columns[0]===c&&n.relation.referencedTable===m.table&&n.relation.referencedColumns.length===1&&n.relation.referencedColumns[0]===f})?null:n})).then(n=>n.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,n,o,s,a){let l=o?C(o):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 Ve=class{};Ve.modelCaseConvention="camel",Ve.databaseCaseConvention="snake";var Bf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");return o+=n.final("hex"),`${r.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},kf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=String(t).trim(),[n,o]=r.split(":");if(!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=n.toLowerCase(),a=o.toLowerCase(),l=Pe.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 S("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Kf=(i,t)=>{try{let e=Pe.randomBytes(32),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");o+=n.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Qf=(i,t)=>{try{let e=String(t).trim(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=privateDecrypt(i,Buffer.from(n,"hex")),a=Pe.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(o,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new S("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var z=class{static defineMetadata(t,e,r,n){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let o=this.store.get(r);o||(o=new Map,this.store.set(r,o));let s=o.get(n);s||(s=new Map,o.set(n,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 n=e;for(;n;){let o=this.store.get(n);if(o){let s=o.get(r);if(s&&s.has(t))return s.get(t)}n=Object.getPrototypeOf(n);}}};z.store=new WeakMap;var Vl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ul=Vl.length,Ph=10,Eh=16,Bh=(i,t)=>{let e="";for(let r=0;r<t;r++){let n=i%Ul;e=Vl.charAt(n)+e,i=(i-n)/Ul;}return e},kh=i=>{let t=ie().crypto.randomBytes(i),e="";for(let r=0;r<i;r++){let n=t[r];e+=Vl.charAt(n%Ul);}return e},Lf=()=>{let i=Math.floor(Date.now()/1e3),t=Bh(i,Ph),e=kh(Eh);return t+e};var Xr=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var en=class extends Oe{constructor(e,r,n){super(e,r);this.type="hasMany";this.foreignKey=n,this.type="hasMany";}};var tn=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var rn=class extends Oe{constructor(e,r,n){super(e,r);this.type="manyToMany";this.primaryModel=n.primaryModel,this.relatedModel=e.table,this.throughModel=n.throughModel,this.leftForeignKey=n.leftForeignKey,this.rightForeignKey=n.rightForeignKey;}};function _(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let n=e.constructor;if(t){if(z.getMetadata(Ct,e))throw new S("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");z.defineMetadata(Ct,r,e),z.defineMetadata(Ct,r,e.constructor);}let o=i.databaseName??H(r,n.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??qe(n.table,r),autoUpdate:i.autoUpdate,autoCreate:i.autoCreate,databaseName:o,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,unsigned:i.unsigned,zerofill:i.zerofill,stringMode:i.stringMode,expression:i.expression,constraints:{nullable:i.nullable,default:i.default}};s.validate=i.validate;let a=z.getMetadata(jr,e)||[];a.push(s),z.defineMetadata(jr,a,e);}}_.primary=Kh;_.date=tg;_.datetime=rg;_.timestamp=ng;_.time=og;_.boolean=eg;_.json=sg;_.uuid=Fh;_.ulid=Uh;_.integer=Lh;_.bigInteger=Hh;_.float=Qh;_.decimal=zh;_.increment=Wh;_.bigIncrement=jh;_.string=Vh;_.text=Jh;_.binary=Gh;_.enum=Yh;_.encryption={symmetric:Zh,asymmetric:Xh};_.computed=ig;function Kh(i={}){return _({...i,primaryKey:true})}function Qh(i={}){return _({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 Lh(i={}){return _({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function Wh(i={}){return _({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 jh(i={}){return _({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 Fh(i={}){return _({type:"uuid",...i,prepare:t=>t||ie().crypto.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function Uh(i={}){return _({type:"ulid",...i,prepare:t=>t||Lf(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Vh(i={}){return _({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Jh(i={}){return _({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Hh(i={}){return _({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 zh(i={}){return _({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 Gh(i={}){return _({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Yh(i,t={}){return _({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Zh(i){return _({...i,prepare:t=>t&&Bf(i.key,t),serialize:t=>t&&kf(i.key,t)})}function Xh(i){return _({...i,prepare:t=>t&&Kf(i.publicKey,t),serialize:t=>t&&Qf(i.privateKey,t)})}function eg(i={}){return _({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function tg(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"DATE_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"date",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"DATE_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...o.openApi||{}}})}function rg(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"ISO",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"datetime",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"ISO",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function ng(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"TIMESTAMP",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"timestamp",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"TIMESTAMP",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function og(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"TIME_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"time",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"TIME_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},stringMode:t,openApi:{type:"string",format:"time",description:"HH:mm:ss",...o.openApi||{}}})}function sg(i={}){return _({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 ig(i,t={}){return _({...t,expression:i})}function Wf(i){try{return z.getMetadata(jr,i.prototype)||[]}catch{return []}}function jf(i){return z.getMetadata(Ql,i.prototype)||[]}function Ff(i){return (z.getMetadata(Ql,i.prototype)||[]).map(e=>{let{type:r,model:n,columnName:o,foreignKey:s}=e,a=C(s),l=n();switch(r){case "belongsTo":return new Xr(l,o,a);case "hasOne":return new tn(l,o,a);case "hasMany":return new en(l,o,a);case "manyToMany":if(!e.manyToManyOptions)throw new S("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=n();return new rn(u,o,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:C(e.manyToManyOptions.throughModel),leftForeignKey:C(e.manyToManyOptions.leftForeignKey),rightForeignKey:C(e.manyToManyOptions.rightForeignKey)});default:throw new S("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Uf(i){return z.getMetadata(Ct,i)||z.getMetadata(Ct,i.prototype)}function Vf(i){return z.getMetadata(Mf,i.prototype)||[]}function Jf(i){return z.getMetadata(xf,i.prototype)||[]}function Hf(i){return z.getMetadata(Of,i.prototype)||[]}var ye=class{};ye.columns=new WeakMap,ye.byName=new WeakMap,ye.byDatabaseName=new WeakMap;var Ae=class extends Ve{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 Uf(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=ye.columns.get(this);return t||(t=Wf(this),ye.columns.set(this,t)),t}static getColumnsByName(){let t=ye.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),ye.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=ye.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),ye.byDatabaseName.set(this,t)),t}static getRelations(){return jf(this)}static getIndexes(){return Vf(this)}static getUniques(){return Jf(this)}static getChecks(){return Hf(this)}static async validate(t){var s,a;let e=this.getColumns(),r={},n=this.primaryKey,o=n&&t?.[n]!==void 0?"update":"insert";for(let l of e){if(l.expression)continue;let u=l.validate;if(!u)continue;let d=t?t[l.columnName]:void 0,c=Array.isArray(u)?u:[u];for(let m of c)try{let p=await m(d,{model:this,column:l.columnName,operation:o,data:t});if(!(p&&p.valid)){let h=p&&p.message||"Validation failed";(r[s=l.columnName]||(r[s]=[])).push(h);}}catch{(r[a=l.columnName]||(r[a]=[])).push("Validation error");}}if(Object.keys(r).length>0)throw new Pt(r);return {valid:true}}};Ae.zodEngine=null,Ae.softDeleteColumn="deletedAt",Ae.softDeleteValue=bt();var Mt=class extends N{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};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 re=class extends N{constructor(e,r=[],n,o=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=n,this.disableReturning=o;}};var Ce=class extends N{constructor(e,r,n,o="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=n,this.mode=o,this.returning=s;}};var xt=class extends N{constructor(e=[],r="inserted"){super("returning");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="returning";this.file="returning";this.columns=e,this.prefix=r;}};var Ee=class extends N{constructor(e,r=[],n=[],o=false){super("update",o);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=n;}};var M=class extends N{constructor(e,r,n=false,o,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=n,this.operator=o,this.value=s;}};var $e=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 j=class extends M{constructor(e,r,n=false,o,s,a=false,l,u){super(e,r,n,"=",s,a);this.file="where_json";this.jsonOperator=o,this.value=s,this.path=l,this.comparisonOperator=u;}};var Re=class extends N{constructor(e,r,n,o="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=n,this.chainsWith=` ${o}`;}};var zf;zf=Symbol.toStringTag;var G=class{constructor(t,e,r,n){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=n;this[zf]="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 ag=(i,t,e,r,n,o=false)=>{let s=Object.create(t.prototype);for(let a of Object.keys(i)){let l=i[a],u=e.get(a),d=a;u||(u=r.get(a),u&&(d=u.columnName));let c=u!==void 0,m=o?true:n?n.has(d):true;if(c){if(!m)continue;if(l===null){s[d]=null;continue}if(u?.serialize){let p=u.serialize(l);if(p!==null&&typeof p?.then=="function")throw new Error(`hysteria-orm: column "${d}" on model "${t.name}" has an async serialize function, but serializers must be synchronous. Move async work to prepare or a getter.`);s[d]=p;continue}s[d]=l;continue}(!o||n&&n.has(d))&&(s[d]=l);}if(n)for(let a of n)a in s||(s[a]=null);return s},he=(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),n=t.getColumnsByDatabaseName(),o=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let p=u.match(/\s+as\s+(.+)$/i);p&&s.push(p[1].trim());continue}let c=u;if(c.includes(".")&&(c=c.split(".").pop()),c==="*")continue;let m=r.get(c)?.columnName??c;s.push(m);}let a=s.length?new Set(s):null,l=i.map(u=>ag(u,t,r,n,a,o));return l.length===1?l[0]:l};var Ft=class{constructor(t){this.observers=t??[];}add(t){this.observers.push(t);}async notifyBefore(t){for(let e of this.observers)e?.onBeforeQuery&&await e.onBeforeQuery(t);}async notifyAfter(t,e){for(let r of this.observers)r?.onAfterQuery&&(t.result??(t.result=e),await r.onAfterQuery(t));}async notifyError(t){for(let e of this.observers)e?.onQueryError&&await e.onQueryError(t);}},Gf=i=>{if(!i)return "OTHER";let t=i.trim().toUpperCase();return t.startsWith("SELECT")?"SELECT":t.startsWith("INSERT")?"INSERT":t.startsWith("UPDATE")?"UPDATE":t.startsWith("DELETE")?"DELETE":"OTHER"};var nn=ie();function Jl(i){let t=nn.timing.now()-i;return Math.round(t*100)/100}var J=async(i,t,e,r,n="rows",o)=>{await e.ensureConnected();let s={id:nn.crypto.randomUUID(),sql:i,params:t,model:void 0,operation:Gf(i),timestamp:nn.timing.now()};try{let u=e.observerChain;u&&typeof u.notifyBefore=="function"&&await u.notifyBefore(s);}catch{}let a=nn.timing.now(),l=u=>{o?.shouldNotLog||ct(i,e.logs,t,e.inputDetails.queryFormatOptions,r,u);};try{let u=e.driverAdapter;if(!u)throw new S("ExecSql","CONNECTION_NOT_ESTABLISHED");let d=o?.timeout,c=d?new AbortController:void 0,m,p=lg(()=>u.execute(i,t,{returning:n,sqlLiteOptions:o?.sqlLiteOptions,signal:c?.signal,connection:e.sqlConnection}),e.inputDetails.connectionPolicies?.retry,e.logs),h;try{d&&c?(h=await Promise.race([p,new Promise((f,T)=>{m=setTimeout(()=>{let w=new S("ExecSql::timeout","QUERY_TIMEOUT",new Error(`Query exceeded the ${d.ms}ms timeout`));d.cancel&&c.abort(w),T(w);},d.ms);})]),p.catch(()=>{})):h=await p;}finally{m&&clearTimeout(m);}try{let f=Jl(a),T=e.observerChain;if(T&&typeof T.notifyAfter=="function"){let w={...s,duration:f,result:h};await T.notifyAfter(w);}}catch{}return l(Jl(a)),u.extract(h,n)}catch(u){throw l(Jl(a)),u}},on=async(i,t,e,r={},n)=>{let o=e.driverAdapter;if(!o)throw new S("ExecSqlStreaming","CONNECTION_NOT_ESTABLISHED");return await o.stream(i,t,{...r,connection:e.sqlConnection??void 0},{onData:n.onData})};async function lg(i,t={maxRetries:0,delay:0},e=false){let r=0,n=t.maxRetries||0,o=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<n)return r++,Nu(`Retrying sql in ${o}ms (attempt ${r}/${n})`,"info",e),await new Promise(l=>setTimeout(l,o)),s();throw a}}return s()}var Y=class extends N{constructor(e,r,n,o,s){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=n,this.isRawValue=o??false,this.distinct=s;}};var Ut=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Ff(t),this.modelRelationsMap=new Map(this.modelRelations.map(n=>[n.columnName,n]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new S("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function sn(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}}var Ot=i=>typeof i=="number"?i:parseFloat(i);var X=class extends N{constructor(e,r,n=false,o,s,a=false,l,u){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=` ${r}`,this.isNegated=n,this.operator=o,this.value=s,this.subquery=l,this.group=u;}};var an=class extends N{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var ln=class extends N{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Je=class extends N{constructor(e,r,n,o="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=n,this.jsonOperator=o,this.isRawValue=s;}};var se=class extends N{constructor(e,r,n,o="inner",s,a=false,l){super(`${o} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=n,this.type=o,this.on=s,this.additionalConditions=l;}};var Vt=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 un=class extends N{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var dn=class extends N{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Jt=class extends N{constructor(e,r="asc",n=false){super("order by",n);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var mn=class mn{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=mn.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 Vt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Vt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Jt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Jt(t,"asc",true)),this}limit(t){return typeof t!="number"&&g.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new un(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new dn(t),this}};mn.EMPTY_MAP=new Map;var cn=mn;var nt=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 n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",false,n,o)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",false,n,o)),this}whereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}andWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}orWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",true,n,o)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new M(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new M(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 M(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new M(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 M(t,"and",false,"in",e)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",false,"in",e)),this):(this.whereNodes.push(new M("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"and",true,"in",e)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",true,"in",e)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new M(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new M(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new M(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new M(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 M(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 M(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 M(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 M(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 $e(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 $e(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new M(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new M(t,"or",true,"=",e??[],true)),this}};var pn=class extends cn{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}crossJoin(t,e){let r=typeof t=="string"?t:t.table;return this.joinNodes.push(new se(e?`${r} as ${e}`:r,"","","cross",{operator:"="})),this}using(...t){let e=this.joinNodes[this.joinNodes.length-1];if(!e||!t.length||e.isRawValue||e.type==="cross"||e.type==="natural")throw new S("JoinQueryBuilder::using","USING_REQUIRES_JOIN");return e.using=t.map(r=>String(r)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,n,o){if(e===void 0)return this.join(typeof t=="string"?t:t.table);let s=r,a=n,l=typeof n=="function"?n:o;if(!s){if(!this.model.primaryKey)throw new S("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,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","inner",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","left",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","right",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,n,o){let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var fn=class extends pn{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[a,l]=r;this.modelSelectedColumns.push(l);let u=this.resolveComputedColumn(a);if(u){this.selectNodes.push(new Y(`(${u.expression}) as ${l}`,void 0,void 0,true));return}let d=H(a,this.model.databaseCaseConvention);this.selectNodes.push(new Y(d,l));return}let n=r;this.modelSelectedColumns.push(n);let o=this.resolveComputedColumn(n);if(o){this.selectNodes.push(new Y(`(${o.expression}) as ${o.alias}`,void 0,void 0,true));return}let s=H(n,this.model.databaseCaseConvention);this.selectNodes.push(new Y(s));}),this}selectRaw(e){return this.selectNodes.push(new Y(e,void 0,void 0,true)),this}selectFunc(e,r,n){return this.selectNodes.push(new Y(r,n,e)),this}countDistinct(e,r){return this.selectNodes.push(new Y(e,r,"count",false,true)),this}sumDistinct(e,r){return this.selectNodes.push(new Y(e,r,"sum",false,true)),this}avgDistinct(e,r){return this.selectNodes.push(new Y(e,r,"avg",false,true)),this}rank(e,r={}){return this.pushWindow("rank",e,r)}denseRank(e,r={}){return this.pushWindow("dense_rank",e,r)}rowNumber(e,r={}){return this.pushWindow("row_number",e,r)}pushWindow(e,r,n){return this.selectNodes.push(new Y(new Fr(e,Df(n.partitionBy),Af(n.orderBy)),r)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}resolveComputedColumn(e){let r=this.model.getColumnsByName?.();if(!r||r.size===0)return;let n=e.includes(".")?e.split(".").pop():e,o=r.get(n);if(o?.expression)return {expression:o.expression,alias:o.databaseName||n}}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 an,this}distinctOn(...e){return this.distinctOnNode=new ln(e),this}selectJson(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract")),this}selectJsonText(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract_text")),this}selectJsonArrayLength(e,r,n){return this.selectNodes.push(new Je(e,r,n,"array_length")),this}selectJsonKeys(e,r,n){return this.selectNodes.push(new Je(e,r,n,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Je(e,"",r,"raw",true)),this}};var yn=class extends fn{constructor(e,r,n=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=n;}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,n){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&n===void 0?this.andWhereSubQuery(e,"in",r):r instanceof B&&n===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function")?this.andWhereSubQuery(e,r,n):this.andWhere(e,r,n)}andWhere(e,r,n){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",false,o,s)),this}orWhere(e,r,n){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",false,o,s)),this}whereColumn(e,r,n){return this.andWhereColumn(e,r,n)}andWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"and",false,o,new x(s))),this}orWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"or",false,o,new x(s))),this}whereNotColumn(e,r,n){return this.andWhereNotColumn(e,r,n)}andWhereNotColumn(e,r,n){return this.pushNotColumnWhere("and",e,r,n)}orWhereNotColumn(e,r,n){return this.pushNotColumnWhere("or",e,r,n)}pushNotColumnWhere(e,r,n,o){let s="!=",a=false,l;return o!==void 0?(s=n,l=o,a=true):l=n,this.whereNodes.push(new M(r,e,a,s,new x(l))),this}whereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}andWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}orWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",true,o,s)),this}whereBetween(e,r,n){return this.andWhereBetween(e,r,n)}andWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"and",false,"between",[r,n])),this}orWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"or",false,"between",[r,n])),this}whereNotBetween(e,r,n){return this.andWhereNotBetween(e,r,n)}andWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"and",true,"between",[r,n])),this}orWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"or",true,"between",[r,n])),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 M(e,"and",false,"in",r)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",false,"in",r)),this):(this.whereNodes.push(new M("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 M(e,"and",true,"in",r)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",true,"in",r)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new M(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new M(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new M(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new M(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"and",false,n?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"or",false,n?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"or",true,n?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"or",false,"=",r,true)),this}having(e,r,n){return this.andHaving(e,r,n)}andHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"and",false,o,s)),this}orHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"or",false,o,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new X(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new X(e,"or",false,"=",[],true)),this}havingNull(e){return this.andHavingNull(e)}andHavingNull(e){return this.havingNodes.push(new X(e,"and",false,"is null",void 0)),this}orHavingNull(e){return this.havingNodes.push(new X(e,"or",false,"is null",void 0)),this}havingNotNull(e){return this.andHavingNotNull(e)}andHavingNotNull(e){return this.havingNodes.push(new X(e,"and",false,"is not null",void 0)),this}orHavingNotNull(e){return this.havingNodes.push(new X(e,"or",false,"is not null",void 0)),this}havingIn(e,r){return this.andHavingIn(e,r)}andHavingIn(e,r){return this.pushHavingIn("and",e,r,false)}orHavingIn(e,r){return this.pushHavingIn("or",e,r,false)}havingNotIn(e,r){return this.andHavingNotIn(e,r)}andHavingNotIn(e,r){return this.pushHavingIn("and",e,r,true)}orHavingNotIn(e,r){return this.pushHavingIn("or",e,r,true)}havingBetween(e,r){return this.andHavingBetween(e,r)}andHavingBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"between",r)),this}orHavingBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"between",r)),this}havingNotBetween(e,r){return this.andHavingNotBetween(e,r)}andHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"not between",r)),this}orHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"not between",r)),this}havingExists(e){return this.andHavingExists(e)}andHavingExists(e){return this.pushHavingExists("and",e,false)}orHavingExists(e){return this.pushHavingExists("or",e,false)}havingNotExists(e){return this.andHavingNotExists(e)}andHavingNotExists(e){return this.pushHavingExists("and",e,true)}orHavingNotExists(e){return this.pushHavingExists("or",e,true)}havingWrapped(e){return this.andHavingWrapped(e)}andHavingWrapped(e){return this.pushHavingGroup("and",e)}orHavingWrapped(e){return this.pushHavingGroup("or",e)}pushHavingIn(e,r,n,o){let s=o?"not in":"in";if(Array.isArray(n))return this.havingNodes.push(new X(r,e,false,s,n)),this;let a=this.buildSubQuery(n);return this.havingNodes.push(new X(r,e,false,s,[],false,a.extractQueryNodes())),this}pushHavingExists(e,r,n){let o=r instanceof B?r:new B(this.model,this.sqlDataSource);return o.isNestedCondition=true,typeof r=="function"&&r(o),this.havingNodes.push(new X("",e,false,n?"not exists":"exists",[],false,o.extractQueryNodes())),this}pushHavingGroup(e,r){let n=new B(this.model,this.sqlDataSource);return n.isNestedCondition=true,r(n),this.havingNodes.push(new X("",e,false,"=",[],false,void 0,n.havingNodes)),this}buildSubQuery(e){if(e instanceof B)return e;let r=new B(this.model,this.sqlDataSource),n=e(r);return n!=null&&"extractQueryNodes"in n?n:r}andWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"and");return this.whereNodes.push(n),this}orWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"or");return this.whereNodes.push(n),this}};var hn=class extends yn{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"or",false,"raw",e)),this}whereJsonObject(t,e){return this.andWhereJsonObject(t,e)}andWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"and",false,"=",e)),this}orWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"or",false,"=",e)),this}whereNotJsonObject(t,e){return this.andWhereNotJsonObject(t,e)}andWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"and",true,"=",e)),this}orWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"or",true,"=",e)),this}whereJsonPath(t,e,r,n){return this.andWhereJsonPath(t,e,r,n)}andWhereJsonPath(t,e,r,n){return this.pushJsonPath("and",t,e,r,n,false),this}orWhereJsonPath(t,e,r,n){return this.pushJsonPath("or",t,e,r,n,false),this}whereJsonSupersetOf(t,e){return this.andWhereJsonSupersetOf(t,e)}andWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotSupersetOf(t,e){return this.andWhereJsonNotSupersetOf(t,e)}andWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"contains",e)),this}orWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"contains",e)),this}whereJsonSubsetOf(t,e){return this.andWhereJsonSubsetOf(t,e)}andWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"subset",e)),this}orWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"subset",e)),this}whereJsonNotSubsetOf(t,e){return this.andWhereJsonNotSubsetOf(t,e)}andWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"subset",e)),this}orWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"subset",e)),this}whereJsonHasNone(t,e){return this.andWhereJsonHasNone(t,e)}andWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"and",false,"has none",e)),this}orWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"or",false,"has none",e)),this}pushJsonPath(t,e,r,n,o,s){let a=new j(e,t,s,"path",o,false,r,n);this.whereNodes.push(a);}};var B=class i extends hn{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.returningNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.comments=[],this.hints=[],this.astParser=new b(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,n]=e;if(typeof r=="function"){let o=new i(this.model,this.sqlDataSource),s=r(o),a=s!=null&&"extractQueryNodes"in s?s:o;return this.selectNodes.push(new Y(a.extractQueryNodes(),n)),this}return this.selectNodes.push(new Y(r.extractQueryNodes(),n)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),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",n=>J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout,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(n=>n[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 S("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:n}=this.unWrap();return this.execSqlWithSlaveHandling("read",async o=>await on(r,n,o,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;r+=n.length,yield n;}}async paginateWithCursor(e,r){if(!this.orderByNodes.length)throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_REQUIRED");let n=this.orderByNodes;if(n.some(m=>m.isRawValue))throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_RAW_NOT_SUPPORTED");let o=n.map(m=>m.column),s=n[0].direction==="desc"?"<":">";if(r){let m=Array.isArray(r.value)?r.value:[r.value];this.andWhere(p=>{for(let h=0;h<o.length;h++){let f=h;p.orWhere(T=>{for(let w=0;w<f;w++)T.where(o[w],"=",m[w]);T.where(o[f],s,m[f]);});}});}this.limit(e+1);let a=await this.many(),l=a.length>e,u=l?a.slice(0,e):a,d=u[u.length-1],c=o.map(m=>m.includes(".")?m.slice(m.lastIndexOf(".")+1):m);return {data:u,hasMore:l,nextCursor:d?{key:c.length===1?c[0]:c,value:c.length===1?d[c[0]]:c.map(m=>d[m])}:null}}lockForUpdate(e={}){return this.lockQueryNodes.push(new Xe("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Xe("for_share",e.skipLocked,e.noWait)),this}forNoKeyUpdate(e={}){return this.assertPgLockStrength("forNoKeyUpdate","FOR NO KEY UPDATE"),this.lockQueryNodes.push(new Xe("for_no_key_update",e.skipLocked,e.noWait)),this}forKeyShare(e={}){return this.assertPgLockStrength("forKeyShare","FOR KEY SHARE"),this.lockQueryNodes.push(new Xe("for_key_share",e.skipLocked,e.noWait)),this}assertPgLockStrength(e,r){if(this.dbType!=="postgres")throw new S(`QueryBuilder::${e}`,`LOCK_STRENGTH_NOT_SUPPORTED_IN_${this.dbType.toUpperCase()}`,new Error(`${r} is only supported by postgres`))}timeout(e,r={}){return this.queryTimeout={ms:e,cancel:r.cancel??false},this}comment(e){return this.assertValidSqlComment(e),this.comments.push(e),this}hintComment(e){this.assertValidSqlComment(e);let r=e.slice(3,-2).trim(),n=this.hints[0];return this.hints=[n?`${n.slice(0,-2).trimEnd()} ${r} */`:`/*+ ${r} */`],this}clearComment(){return this.comments=[],this}clearHintComment(){return this.hints=[],this}assertValidSqlComment(e){let r=()=>{throw new S("QueryBuilder::comment","INVALID_SQL_COMMENT")};(!e.trim().length||e.includes("?"))&&r();let n=(this.dbType==="mysql"||this.dbType==="mariadb")&&e.startsWith("#");if(e.startsWith("--")||n){/[\r\n]/.test(e)&&r();return}if(e.startsWith("/*")&&e.endsWith("*/")&&e.length>=4){let o=e.slice(2,-2);(o.includes("/*")||o.includes("*/"))&&r();return}r();}union(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e,true)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n,true)),this}intersect(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"intersect")),this}except(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"except")),this}resolveSetOperationNodes(e){return typeof e=="string"?e:(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes()}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.buildCountQuery(e);let r=await this.one();return r?Ot(r.total):0}needsDerivedTableCount(){return this.groupByNodes.length>0||this.havingNodes.length>0||this.distinctNode!==null||this.distinctOnNode!==null}buildCountQuery(e="*"){if(!this.needsDerivedTableCount()){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);return}this.clearOrderBy(),this.clearLimit(),this.clearOffset();let r=this.extractQueryNodes();this.withNodes=[],this.distinctNode=null,this.distinctOnNode=null,this.clearSelect(),this.fromNode=new U(r,"g"),this.joinNodes=[],this.whereNodes=[],this.groupByNodes=[],this.havingNodes=[],this.lockQueryNodes=[],this.unionNodes=[],this.comments=[],this.hints=[],this.selectRaw(`count(${e}) as total`);}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?Ot(r.total):0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?Ot(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?Ot(r.total):0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?Ot(r.total):0}async columnInfo(e){let r=typeof this.fromNode.table=="string"?this.fromNode.table:this.model.table,o=await(await this.getSqlDataSource("read")).getTableInfo(r);return e===void 0?o:o.find(s=>s.name===e)}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new S("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let n=new i(this.model,this.sqlDataSource),o=e(n),a=(o!=null&&"extractQueryNodes"in o?o:n).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}withSchema(e){return this.schemaName=e,this}fromRaw(e,r=[]){return this.fromNode=new U(new x(e,r)),this}with(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("materialized",e,s.extractQueryNodes())),this}withNotMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withNotMaterialized","NOT_MATERIALIZED_CTE_NOT_SUPPORTED",new Error("NOT MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("not materialized",e,s.extractQueryNodes())),this}insert(e,r){let n=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,[this.interpreterUtils.stripComputedFromData(n)],r,o),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),l=Object.fromEntries(s.map((p,h)=>[p,a[h]]));this.insertNode=new re(this.fromNode,[l],r,o);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!o)return Array.isArray(m)&&m.length?m[0]:m})}insertMany(e,r){let n=e.map(s=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(s).map(a=>[a,s[a]])))),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,n,r,o),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return o?void 0:[];let s=await Promise.all(e.map(async c=>{let{columns:m,values:p}=this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert",this.dbType);return Object.fromEntries(m.map((h,f)=>[h,p[f]]))}));this.insertNode=new re(this.fromNode,s,r,o);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await J(a,l,u,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!o)return d})}upsert(e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(Object.keys(e)),s=Object.keys(r),a=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(e).map(l=>[l,e[l]])));return this.insertNode=new re(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),d=Object.fromEntries(l.map((f,T)=>[f,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,o,n,[e]);let{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),[d],void 0,true),new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning)]),p=await this.getSqlDataSource("write"),h=await J(c,m,p,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(h)?h:[h]})}upsertMany(e,r,n,o={updateOnConflict:true}){let s=this.interpreterUtils.filterComputedColumns(r),a=n.map(l=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(l).map(u=>[u,l[u]]))));return this.insertNode=new re(new U(this.model.table),a,void 0,true),this.onDuplicateNode=new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let l=[];if(await Promise.all(n.map(async p=>{let{columns:h,values:f}=this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert",this.dbType),T=Object.fromEntries(h.map((w,q)=>[w,f[q]]));l.push(T);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(l,e,s,o,n);let{sql:u,bindings:d}=this.astParser.parse([new re(new U(this.model.table),l,void 0,true),new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,n,o,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=K=>this.interpreterUtils.formatStringColumn("mssql",K),d=[],c=e.map(K=>`select ${a.map(v=>(d.push(K[v]),`@${d.length}`)).join(", ")}`),m=a.map(u).join(", "),p=c.join(" union all "),h=r.map(K=>`target.${u(K)} = source.${u(K)}`).join(" and "),f=n.filter(K=>!r.includes(K)).map(K=>`target.${u(K)} = source.${u(K)}`).join(", "),T=a.map(u).join(", "),w=a.map(K=>`source.${u(K)}`).join(", "),q=o.returning&&o.returning.length?o.returning.map(K=>`inserted.${u(K)}`).join(", "):a.map(K=>`inserted.${u(K)}`).join(", "),R=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",$=`merge into ${l} as target using (${p}) as source (${m}) on ${h} ${R} when not matched then insert (${T}) values (${w}) output ${q};`,A=await this.getSqlDataSource("write"),O=await J($,d,A,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(O)?O:[O]}update(e,r){let n=this.interpreterUtils.stripComputedFromData(e),o=Object.keys(n),s=Object.values(n);this.updateNode=new Ee(this.fromNode,o,s),this.returningNode=this.buildReturningNode("update",r);let a=this.returningNode!==null;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(o,s,"update",this.dbType);this.updateNode=new Ee(this.fromNode,l,u);let{sql:d,bindings:c}=this.astParser.parse(this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes])),m=await this.getSqlDataSource("write");return J(d,c,m,this.dbType,a?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:a?"fetch":"affectedRows"}})})}buildReturningNode(e,r){return !r?.length||!this.interpreterUtils.dialectEmitsReturning(this.dbType)?null:new xt(r,e==="delete"?"deleted":"inserted")}withReturningNode(e){if(!this.returningNode)return e;if(this.dbType==="mssql"){let[r,...n]=e;return [r,this.returningNode,...n]}return [...e,this.returningNode]}truncate(){return this.truncateNode=new qt(this.fromNode),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),n=await this.getSqlDataSource("write");await J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout});})}delete(e){this.deleteNode=new Mt(this.fromNode),this.returningNode=this.buildReturningNode("delete",e);let r=this.returningNode!==null;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:n,bindings:o}=this.astParser.parse(this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes])),s=await this.getSqlDataSource("write");return J(n,o,s,this.dbType,r?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:n=bt()}=e||{};return this.updateNode=new Ee(this.fromNode,[r],[n]),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:o,values:s}=this.interpreterUtils.prepareColumns([r],[n],"update",this.dbType);this.updateNode=new Ee(this.fromNode,o,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return J(a,l,u,this.dbType,"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return it(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),n=lt(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${n}`:n,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new Y("*")]);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=W(this.modelSelectedColumns),e.distinctNode=W(this.distinctNode),e.distinctOnNode=W(this.distinctOnNode),e.selectNodes=W(this.selectNodes),e.withQuery=W(this.withQuery),e.joinNodes=W(this.joinNodes),e.whereNodes=W(this.whereNodes),e.groupByNodes=W(this.groupByNodes),e.havingNodes=W(this.havingNodes),e.orderByNodes=W(this.orderByNodes),e.lockQueryNodes=W(this.lockQueryNodes),e.unionNodes=W(this.unionNodes),e.withNodes=W(this.withNodes),e.comments=[...this.comments],e.hints=[...this.hints],e.schemaName=this.schemaName,e.fromNode=W(this.fromNode),e.limitNode=W(this.limitNode),e.offsetNode=W(this.offsetNode),e.returningNode=W(this.returningNode),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(){if(this.selectNodes.length||(this.selectNodes=[new Y("*")]),this.schemaName){this.fromNode&&typeof this.fromNode.table=="string"&&(this.fromNode.schema=this.schemaName);for(let n of this.joinNodes)n.schema=this.schemaName;}if(this.insertNode)return [this.insertNode,this.onDuplicateNode].filter(Boolean);if(this.updateNode)return this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.deleteNode)return this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.truncateNode)return [this.truncateNode];let e=this.comments.map(n=>new Lt(n)),r=this.hints.length?[new Lt(this.hints.join(" "),true)]:[];return [...this.withNodes,...e,this.distinctNode,this.distinctOnNode,...this.selectNodes,...r,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}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let n=await e(),o=await r();return [n,o]}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 n=await this.getSqlDataSource(e);if(!(n!==this.sqlDataSource))return r(n);try{return await r(n)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:n.host,port:n.port,username:n.username,password:n.password,database:n.database,type:n.getDbType()}),await r(this.sqlDataSource);throw a}}};function Yf(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:ug(i)}function ug(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 Hl=ie(),ot=class i extends B{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Ut(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[n,o]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(n,o.columnName);}expandModelSelectColumns(){let e=this.selectNodes;if(!e.length){if(this.joinNodes.length)return;for(let[,r]of this.modelColumnsMap)r.expression||e.push(new Y(r.databaseName,r.columnName));return}for(let r of e){if(r.isRawValue||r.alias!==void 0||typeof r.column!="string"||r.column.includes(".")||r.column==="*")continue;let n=this.modelColumnsMap.get(r.column);!n||n.expression||(r.alias=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(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(e){let r=await this.one();if(!r)throw new S(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(){await this.model.beforeFetch?.(this),this.expandModelSelectColumns();let r=await super.many();if(!r.length)return [];let n=he(r,this.model,this.modelSelectedColumns);if(!n)return [];let o=Array.isArray(n)?n:[n];return this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(o),o}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){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;yield n,r+=n.length;}}async stream(e={}){await this.model.beforeFetch?.(this),this.expandModelSelectColumns();let{sql:r,bindings:n}=this.unWrap(),o=await this.getSqlDataSource("read");return await on(r,n,o,e,{onData:async(a,l)=>{let u=he([l],this.model,this.modelSelectedColumns);u&&(this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}async paginateWithCursor(e,r){return super.paginateWithCursor(e,r)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{returning:r.returning})}upsert(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return o.upsertMany(s,a,[l],{updateOnConflict:n.updateOnConflict??true,returning:n.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=r.length>0?Object.keys(r[0]):[];return o.upsertMany(e,s,r,{updateOnConflict:n.updateOnConflict??true,returning:n.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource.getTransactionBoundSqlDataSource()??this.sqlDataSource;return new st(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,n){return this.getModelManager(n?.trx).updateRecord(e,r,n)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let n=this.model.primaryKey;if(!n)throw new S(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let o=e[n],s=o?{[n]:o}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,n){let{column:o=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[o]:s};return this.getModelManager(n?.trx).updateRecord(e,a,{returning:n?.returning})}async firstOrInsert(e,r,n){let o=this.getModelManager(n?.trx),s=await o.findOne({where:e});if(s)return s;let a={...e,...r};return o.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,n,o,s={}){if(Array.isArray(n)||(n=[n]),!n.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new S(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=H(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=H(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=n.map((p,h)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...o?o(p,h):{}}));class c extends Ae{static get table(){return a.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await new st(c,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let n=r.returning,o=super.update(e,n);return new G(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>{if(!n||!this.returningNode)return o;let s=await o;return he(s,this.model,n)})}softDelete(e={}){let r=super.softDelete(e);return new G(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>r)}delete(e={}){let r=e.returning,n=super.delete(r);return new G(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>{if(!r||!this.returningNode)return n;let o=await n;return he(o,this.model,r)})}async getCount(e="*"){this.buildCountQuery(e);let r=await this.one();return r?+r.total:0}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?+r.total:0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?+r.total:0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?+r.total:0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?+r.total:0}async paginate(e,r){let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof B)&&typeof e[1]=="string"){let[r,n]=e;return super.select(r,n),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,n){let o,s={strategy:"auto"};typeof r=="function"?(o=r,n&&(s=n)):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,o?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,n){return this.andHavingRelated(e,r,n)}andHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.whereExists(d),this}orHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.orWhereExists(d),this}notHavingRelated(e,r,n){return this.andNotHavingRelated(e,r,n)}andNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.whereNotExists(d),this}orNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=W(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let n=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,n);}));}async processRelationsWithStrategy(e){let r=e.length,n=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),o=async s=>{let a=Yf({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 n)await o(s);return}await Promise.all(n.map(o));}async loadRelationViaJoin(e,r){let n=e.relation,o=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,n,o).many();this.mapJoinedResultsToModels(a,r,n,o);}buildJoinQuery(e,r,n){let o=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)o.selectNodes.push(W(s));else for(let[s,a]of this.model.getColumnsByDatabaseName())a.expression||o.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=W(s);this.qualifyWhereNodeColumns(a,this.model.table),o.whereNodes.push(a);}for(let s of this.groupByNodes)o.groupByNodes.push(W(s));for(let s of this.orderByNodes)o.orderByNodes.push(W(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(o.limitNode=W(this.limitNode)),this.offsetNode&&(o.offsetNode=W(this.offsetNode))),r.type){case "hasOne":case "hasMany":o.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":o.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;o.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),o.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(o,r,e,n);for(let s of e.whereNodes)o.whereNodes.push(W(s));for(let s of e.orderByNodes)o.orderByNodes.push(W(s));return o}selectRelationColumnsWithAlias(e,r,n,o){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=n.selectNodes.filter(m=>typeof m.column=="string"),c=d.some(m=>m.column==="*"||m.column.endsWith(".*"));if(d.length===0||c)for(let[m,p]of u)e.selectRaw(`${a.table}.${m} as ${s}${o}${p.columnName}`);else for(let m of d){let p=m.column,h=p.includes(".")?p.split(".").pop():p,f=u.get(h)||l.get(h),T=f?.databaseName??h,w=m.alias??f?.columnName??h;e.selectRaw(`${a.table}.${T} as ${s}${o}${w}`);}}mapJoinedResultsToModels(e,r,n,o){let{columnName:s,type:a}=n,l=n.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];u.has(c)||u.set(c,[]);let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.get(c).push(m));}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||[];});}else {let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];if(!u.has(c)){let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.set(c,m));}}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||null;});}}extractRelationDataFromRow(e,r,n){let o=`${r}${n}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(o)){let d=u.substring(o.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 M)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Re)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof $e)for(let n of e.nodes)this.qualifyWhereNodeColumns(n,r);}serializeRelationData(e,r){for(let n of Object.keys(e)){let o=r.get(n);o?.serialize&&e[n]!==null&&e[n]!==void 0&&(e[n]=o.serialize(e[n]));}}async loadRelationViaBatch(e,r){let n=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,n);}mapRelatedModelsToModels(e,r,n){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let o=new Map;n.forEach(m=>{let p=m[e.foreignKey];p&&o.set(String(p),m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=null;return}let h=o.get(String(p));m[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;n.forEach(m=>{if(!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=m[e.model.primaryKey];p&&s.set(String(p),m);}),r.forEach(m=>{let p=m[e.foreignKey];if(!p){m[e.columnName]=null;return}let h=s.get(String(p));m[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;n.forEach(m=>{let p=m[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=a.get(String(p))||[];m[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,c=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||H(d,this.model.modelCaseConvention);n.forEach(m=>{let p=m[c];if(p==null)return;let h=String(p);u.has(h)||u.set(h,[]),delete m[c],u.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=u.get(String(p))||[];m[e.columnName]=h;});break;default:throw new S(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,n){return this.getRelatedModelsQueryForRelation(e,r,n).many()}getRelatedModelsQueryForRelation(e,r,n){let o=this.getFilterValuesFromModelsForRelation(r,n);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,o);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,o);let l=Qe(Hl.crypto.randomBytes(6)),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(O=>O.isRawValue?O.column:`${this.interpreterUtils.formatStringColumn(this.dbType,O.column)} ${O.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let c=e.with(u,O=>O.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,o));s&&c.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&c.whereRaw(`rn_${l} > ${a}`);let m=e.modelSelectedColumns.map(O=>fo(O,u,e.model.table));return c.select(...m).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!n.length)return e;let h=e.limitNode?.limit,f=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(O=>O.includes(".")?O:`${r.model.table}.${O}`):[`${r.model.table}.*`];if(!h&&!f)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o);let w=Qe(Hl.crypto.randomBytes(6)),q=`${r.model.table}_cte_${w}`,D=e.orderByNodes.map(O=>{if(O.isRawValue)return O.column;let K=O.column.includes(".")?O.column:`${r.model.table}.${O.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,K)} ${O.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Qe(Hl.crypto.randomBytes(6))}_left_foreign_key`,$=e.with(q,O=>O.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,R]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${D}) as rn_${w}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o));h&&$.whereRaw(`rn_${w} <= ${h+(f||0)}`),f&&$.whereRaw(`rn_${w} > ${f}`);let A=T.map(O=>fo(O,q,e.model.table));return $.select(...A).select([`${q}.${R}`,p.leftForeignKey]).table(q);default:throw new S(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);case "belongsTo":return r.map(n=>n[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);default:throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,n,o){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 S(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}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new S(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}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===u.throughModel&&p.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let c=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${c} = ${m}`),n&&typeof o=="number"&&e.groupByRaw(c).andHavingRaw(`count(*) ${n} ${o}`);return}default:throw new S(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}};function Zf(){return {}}var st=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Zf(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,n])=>{e.orderBy(r,n);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many()}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,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,offset:t.offset});if(e===null)throw t.customError?t.customError:new S(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new S(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one()}insert(t,e={}){let r=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(t).map(u=>[u,t[u]]))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),[r],e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new G(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(q){throw q}let{columns:u,values:d}=this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert",this.sqlType),c={};u.forEach((q,D)=>{let R=d[D];c[q]=R,t[q]??(t[q]=R);});let m=!e.returning||e.returning.length===0,{sql:p,bindings:h}=this.astParser.parse([new re(new U(this.model.table),[c],e.returning,m)]),f=await J(p,h,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(m)return;if(this.sqlType==="mysql")return this.handleMysqlInsert(f,[t],"one",e.returning);let T=f[0];return T?he([T],this.model,e.returning):t})}insertMany(t,e={}){let r=t.map(u=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(u).map(d=>[d,u[d]])))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),r,e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new G(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}let u=t.map(T=>{let{columns:w,values:q}=this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert",this.sqlType),D={};return w.forEach((R,$)=>{let A=q[$];D[R]=A,T[R]??(T[R]=A);}),D}),d=!e.returning||e.returning.length===0,{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),u,e.returning,d)]),p=await J(c,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let h=p;return h.length?he(h,this.model,e.returning)||[]:[]})}upsertMany(t,e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(e),s=r.map(p=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(p).map(h=>[h,p[h]])))),a=new re(new U(this.model.table),s,void 0,true),l=n.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0;new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",l);let d=()=>{let p=this.astParser.parse([a]);return {sql:p.sql,bindings:p.bindings}},c=()=>{let p=this.astParser.parse([a]);return {sql:lt(this.sqlDataSource,p.sql),bindings:p.bindings}},m=()=>{let{sql:p,bindings:h}=c();return it(p,h)};return new G(d,c,m,async()=>{let p=r.map(A=>{let{columns:O,values:K}=this.interpreterUtils.prepareColumns(Object.keys(A),Object.values(A),"insert",this.sqlType);return Object.fromEntries(O.map((le,v)=>[le,K[v]]))});if(this.sqlType==="mssql")return this.executeMssqlMerge(p,t,o,n,r);let h=!n.returning||n.returning.length===0,f=!h&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0,{sql:T,bindings:w}=this.astParser.parse([new re(new U(this.model.table),p,void 0,true),new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",f)]),q=await J(T,w,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(h)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(q.length<r.length&&!(n.updateOnConflict??true)){let K=t[0],le=r.map(ne=>ne[K]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(K,le).many()}return he(q,this.model,n.returning)||[]}let D=t[0],R=r.map(A=>A[D]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(D,R).many()})}async executeMssqlMerge(t,e,r,n,o){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=A=>this.interpreterUtils.formatStringColumn("mssql",A),u=[],d=t.map(A=>`select ${s.map(K=>(u.push(A[K]),`@${u.length}`)).join(", ")}`),c=s.map(l).join(", "),m=d.join(" union all "),p=e.map(A=>`target.${l(A)} = source.${l(A)}`).join(" and "),h=r.filter(A=>!e.includes(A)).map(A=>`target.${l(A)} = source.${l(A)}`).join(", "),f=s.map(l).join(", "),T=s.map(A=>`source.${l(A)}`).join(", "),w=n.returning&&n.returning.length?n.returning.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "):s.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "),D=(n.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",R=`merge into ${a} as target using (${m}) as source (${c}) on ${p} ${D} when not matched then insert (${f}) values (${T}) output ${w};`,$=await J(R,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});if($.length===0&&!(n.updateOnConflict??true)){let A=e[0],O=o.map(le=>le[A]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(A,O).many()}return $}async updateRecord(t,e,r){let n=new Set(this.model.getColumns().map(w=>w.columnName)),o=Object.keys(e).filter(w=>n.has(w)),s=o.map(w=>e[w]),{columns:a,values:l}=this.interpreterUtils.prepareColumns(o,s,"update",this.sqlType),{primaryKey:u}=this.model;if(!u)throw new S(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 c=r?.returning??[],m=c.length>0&&!this.interpreterUtils.hasComputedColumn(c)&&this.interpreterUtils.shouldFetchNatively(this.sqlType,"update"),{sql:p,bindings:h}=this.astParser.parse([new Ee(new U(this.model.table),a,l),new M(u,"and",false,"=",t),...m?[new xt(c)]:[]]),f=await J(p,h,this.sqlDataSource,this.sqlType,m?"rows":"affectedRows",m?{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}:void 0);if(!c.length)return;if(m){if(!f.length)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return he([f[0]],this.model,c)}let T=await this.findOneByPrimaryKey(t,r?.returning);if(!T)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return T}async deleteRecord(t){if(!this.model.primaryKey)throw new S(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new M(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:n}=this.astParser.parse([new Mt(new U(this.model.table)),e]);await J(r,n,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new ot(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,n){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?he([a],this.model):null}return he(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(...n??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let o=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...n||["*"]).whereIn(this.model.primaryKey,o).many();return r==="one"?s.length?s[0]:null:s}handleWhereCondition(t,e,r=false){if(e)for(let[n,o]of Object.entries(e))n==="$and"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{for(let l of o)this.handleWhereCondition(a,l,false);}):n==="$or"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of o)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,n,o,r);}applyFieldCondition(t,e,r,n=false){if(r==null||typeof r!="object"){r===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",r):t.where(e,"=",r);return}let o=r,s=o.op,a=o.value;switch(s){case "$eq":a===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?n?t.orWhereNotNull(e):t.whereNotNull(e):n?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":n?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":n?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":n?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":n?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;n?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;n?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":n?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":n?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":n?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":n?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":n?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":n?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":n?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":n?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":n?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":n?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:n?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var zl=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??bt()});Dt();var be=class{constructor(t){this.options=t;}static async createDriver(t){throw new S("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};ue();var Ht=class Ht extends be{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new Ht(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new L("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new L("mongodb");return new Ht(this.mongoClient)}};Ht.mongoClient=null;var gn=Ht;ue();var zt=class zt extends be{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new zt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new L("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new L("mssql");return new zt(this.mssqlClient)}};zt.mssqlClient=null;var bn=zt;ue();var Gt=class Gt extends be{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Gt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new L("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new L("mysql2");return new Gt(this.mysqlClient)}};Gt.mysqlClient=null;var Tn=Gt;ue();var Yt=class Yt extends be{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Yt(this.pgClient);let e=await import('pg').catch(()=>{throw new L("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new L("pg");return new Yt(this.pgClient)}};Yt.pgClient=null;var wn=Yt;ue();var Zt=class Zt extends be{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Zt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new L("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new L("sqlite3");return new Zt(this.sqlite3Client)}};Zt.sqlite3Client=null;var Sn=Zt;var me=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Tn.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await wn.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Sn.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await gn.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await bn.createDriver(),this.mssqlDriver;default:throw new S(`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;default:return null}}};me.mysqlDriver=null,me.pgDriver=null,me.sqliteDriver=null,me.mssqlDriver=null,me.mongodbDriver=null;Dt();ue();var Nn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.coerceNumericTypes&&!e.driverOptions?.types?{getTypeParser:(o,s)=>{let a=!s||s==="text";return a&&o===20?l=>BigInt(l):a&&o===1700?l=>Number.parseFloat(l):r.types.getTypeParser(o,s)}}:void 0;this.pool=new r.Pool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions,...n?{types:n}:{}});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.connect()}releaseConnection(t){t?.release();}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION"),e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`);}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=0,o=t.replace(/\?/g,()=>`$${++n}`);if(!r.signal)return (r.connection??this.pool).query(o,e);let s=r.connection??await this.pool.connect(),a=!r.connection,l=()=>{let u=s.processID;u!=null&&this.pool.query("SELECT pg_cancel_backend($1)",[u]).catch(()=>{});};r.signal.addEventListener("abort",l,{once:true});try{return await s.query(o,e)}finally{r.signal.removeEventListener("abort",l),a&&s.release();}}extract(t,e){return e==="rows"?t.rows:e==="raw"?t:t.rowCount}async stream(t,e,r,n){let o=r.connection,s=!o,a=o??await this.pool.connect(),l=await import('pg-query-stream').catch(()=>{throw new L("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,c=t.replace(/\?/g,()=>`$${++d}`),m=new l.default(c,e,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(m),h=0,f=false,T=false,w=q=>{if(s)try{a.release(q);}catch{}};return p.on("data",q=>{if(n.onData){h++,Promise.resolve(n.onData(u,q)).then(()=>{h--,f&&h===0&&!T&&(w(),u.end());}).catch(D=>{T=true,w(D),u.destroy(D);});return}u.write(q);}),p.on("end",()=>{f=true,h===0&&!T&&(w(),u.end());}),p.on("error",q=>{T=true,w(q),u.destroy(q);}),u}};var qn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=r.createPool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.getConnection()}releaseConnection(t){t?.release();}async beginTransaction(t,e){e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`),await t.beginTransaction();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){if(!r.signal)return (r.connection??this.pool).query(t,e);let n=r.connection??await this.pool.getConnection(),o=!r.connection,s=()=>{let a=n.threadId;a!=null&&this.pool.query(`KILL QUERY ${Number(a)}`).catch(()=>{});};r.signal.addEventListener("abort",s,{once:true});try{return await n.query(t,e)}finally{r.signal.removeEventListener("abort",s),o&&n.release();}}extract(t,e){let r=t;return e==="affectedRows"?r[0]?.affectedRows??0:e==="raw"?t:r[0]}async stream(t,e,r,n){let o=this.pool,s=r.connection??await o.getConnection(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=s.connection.query(t,e).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),d=0,c=false,m=false,p=()=>{try{s.release();}catch{}};return u.on("data",h=>{if(n.onData){d++,Promise.resolve(n.onData(a,h)).then(()=>{d--,c&&d===0&&!m&&(p(),a.end());}).catch(f=>{m=true,p(),a.destroy(f);});return}a.write(h);}),u.on("end",()=>{c=true,d===0&&!m&&(p(),a.end());}),u.on("error",h=>{m=true,p(),a.destroy(h);}),a.on("close",()=>{p();}),a}};var Cn=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=new r.Database(String(e.database??":memory:"),e.driverOptions?.mode??void 0,n=>{if(n)throw new S("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});}createPool(){}async closePool(){await new Promise((t,e)=>{this.pool.close(r=>{r&&e(r),t();});});}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){return await this.promisify(t,e,r)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.pool;return new Gl(o,t,e,{onData:n.onData})}promisify(t,e,r){let n=r.sqlLiteOptions??{},o=n.mode||"fetch",s=n.customConnection??r.connection??this.pool;if(["begin","begin transaction","commit","rollback"].includes(t.trim().toLowerCase()))return new Promise((u,d)=>{s.run(t,e,function(c){c&&d(c),u(this.changes);});});if(o==="fetch")return new Promise((u,d)=>{s.all(t,e,(c,m)=>{c&&d(c),u(m||[]);});});if(!n?.typeofModel)return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});});if(o==="insertOne"||o==="insertMany"){let u=`${t} returning *`;return new Promise((d,c)=>{s.all(u,e,(m,p)=>{if(m)return c(m);d(p||[]);});})}return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});})}},Gl=class extends Readable{constructor(t,e,r=[],n){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=n;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(n,o)=>{if(n){r=true,this.emit("error",n);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,o)).then(()=>{if(!r){if(s){this.push(a);return}this.push(o);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},n=>{if(n){r=true,this.emit("error",n);return}e=true,t===0&&!r&&this.push(null);});}};ue();var Rn=class{constructor(t,e,r){this.dialect="mssql";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.driverOptions,{options:o,...s}=n??{};this.pool=new r.ConnectionPool({server:e.host??"localhost",port:e.port,database:e.database,user:e.username,password:e.password,...s,options:{trustServerCertificate:E.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...o,abortTransactionOnError:false,enableImplicitTransactions:false}});}async createPool(){await this.pool.connect();}async closePool(){await this.pool.close();}async reserveConnection(){return this.pool.transaction()}releaseConnection(){}async beginTransaction(t,e){if(e.isolationLevel){let r=await this.getMssqlTransactionLevel(e.isolationLevel);await t.begin(r);return}await t.begin();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){let n=this.pool,o=r.connection?r.connection.request():n.request();e.forEach((l,u)=>{o.input(`p${u}`,l);});let s=0,a=t.replace(/\?|@(\d+)/g,()=>`@p${s++}`);if(r.signal){let l=()=>{try{o.cancel();}catch{}};r.signal.addEventListener("abort",l,{once:true});try{return await o.query(a)}finally{r.signal.removeEventListener("abort",l);}}return o.query(a)}extract(t,e){return e==="affectedRows"?t.rowsAffected[0]:e==="raw"?t:t.recordset}async stream(t,e,r,n){let o=r.connection??this.pool,s=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),a=o.request();a.stream=true,e.forEach((p,h)=>{a.input(`p${h}`,p);});let l=0,u=t.replace(/\?|@(\d+)/g,()=>`@p${l++}`),d=0,c=false,m=false;return a.on("row",p=>{if(!m){if(n.onData){d++,Promise.resolve(n.onData(s,p)).then(()=>{d--,c&&d===0&&!m&&s.end();}).catch(h=>{m=true,s.destroy(h);});return}s.write(p);}}),a.on("error",p=>{m=true,s.destroy(p);}),a.on("done",()=>{c=true,d===0&&!m&&s.end();}),a.query(u),s}async getMssqlTransactionLevel(t){let e=await import('mssql').then(r=>r.default.ISOLATION_LEVEL).catch(r=>{throw g.error(r),new L("mssql")});switch(t){case "READ UNCOMMITTED":return e.READ_UNCOMMITTED;case "READ COMMITTED":return e.READ_COMMITTED;case "REPEATABLE READ":return e.REPEATABLE_READ;case "SERIALIZABLE":return e.SERIALIZABLE;default:throw new S("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${t}`)}}};var yg=()=>{ge({name:"pg",dialects:["postgres","cockroachdb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Nn(i,t,e)}}),ge({name:"mysql2",dialects:["mysql","mariadb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new qn(i,t,e)}}),ge({name:"sqlite3",dialects:["sqlite"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Cn(i,t,e)}}),ge({name:"mssql",dialects:["mssql"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Rn(i,t,e)}});};yg();var Sg=async i=>{if(i==="bun"){await(await Promise.resolve().then(()=>(ay(),iy))).registerBunDrivers();return}if(i==="web"){(await Promise.resolve().then(()=>(tu(),eu))).registerWebDrivers();return}if(i==="react-native"){await(await Promise.resolve().then(()=>(tu(),eu))).registerReactNativeDrivers();return}},Dn=async(i,t)=>{let e=ur(t?.jsEnvironment);await Sg(e);let r=await ey(i,e,t?.driver,t);return await r.createPool(),r};var er=class er{constructor(){}static run(t,e){return er.storage.run(t,e)}static getTransaction(){return er.storage.getStore()}};er.storage=new AsyncLocalStorage;var He=er;var tr=class i{constructor(t,e,r=false,n=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Qe(ie().crypto.randomBytes(16)),this.isolationLevel=e,this.isNested=r,this.nestingDepth=n;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await He.run(e,()=>t(e));return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){if(this.getIsolationLevelQuery(),this.isNested){let r=this.getSavePointName();this.sql.type==="mssql"?await this.sql.rawQuery(`SAVE TRANSACTION ${r}`):await this.sql.rawQuery(`SAVEPOINT ${r}`),this.isActive=true;return}(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("BEGIN TRANSACTION",this.sql.logs);let t=this.sql.driverAdapter,e=this.sql.sqlConnection;if(!t||!e)throw new S("TRANSACTION::transaction","CONNECTION_NOT_ESTABLISHED");await t.beginTransaction(e,{isolationLevel:this.isolationLevel,rawQuery:(r,n)=>this.sql.rawQuery(r,n??[])}),this.isActive=true;}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("COMMIT",this.sql.logs),e&&r&&await e.commitTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new S("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("ROLLBACK",this.sql.logs),e&&r&&await e.rollbackTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async releaseConnection(){if(this.connectionReleased)return;let t=null;try{this.sql.driverAdapter?.releaseConnection(this.sql.sqlConnection);}catch(e){t=e,g.error(e);}this.sql.sqlConnection=null;try{await this.sql.disconnect();}catch(e){g.warn(`Transaction::releaseConnection - disconnect failed: ${e?.message??e}`);}if(this.connectionReleased=true,t)throw t}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new S("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new S("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}};var ru=Symbol.for("hysteria.orm.SqlDataSource"),my,py,Be=class i extends(py=kt,my=ru,py){constructor(e){super(e);this[my]=true;this.globalTransaction=null;this.globalTransactionLock=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.lockConnection=null;this.lockKeyToId=new Map;this.driverAdapter=null;this.id=ie().crypto.randomUUID();this.logicalSourceId=ie().crypto.randomUUID();this.cacheAdapter=new hr;this.migrationConfig={path:E.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.zodEngine=null;this.lazyLoad=false;this.connecting=null;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:vt(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(n=>new i(n)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure,this.lazyLoad=e?.lazyLoad??false,this.clsEnabled=e?.clsEnabled??true;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&ru in e&&e[ru]===true}get isClsEnabled(){return this.clsEnabled}getOnSlaveServerFailure(){return this.onSlaveServerFailure}addObserver(e){return this.observerChain||(this.observerChain=new Ft([])),this.observerChain.add(e),this}static async useConnection(e,r){let n=new i(e);await n.connect();try{await r(n),n.isConnected&&await n.disconnect();}catch(o){throw n.isConnected&&await n.disconnect(),o}}async connect(){if(this.isConnected)throw new S("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");try{this.driverAdapter=await Dn(this.sqlType,this.inputDetails),this.sqlPool=this.driverAdapter.pool??null,this.ownsPool=!0,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.driverAdapter=await Dn(e.sqlType,e.inputDetails),e.sqlPool=e.driverAdapter.pool??null,e.ownsPool=!0;}));}catch(e){this.sqlPool=null,this.ownsPool=false;for(let r of this.slaves)r.ownsPool&&(r.sqlPool=null,r.ownsPool=false);throw e}}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new S("SqlDataSource::ensureConnected","CONNECTION_NOT_ESTABLISHED");this.connecting||(this.connecting=this.connect().finally(()=>{this.connecting=null;})),await this.connecting;}}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){let e=this;return new Proxy(this._models,{get(r,n){if(typeof n=="string"&&n in r)return e.from(r[n])}})}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}getTransactionBoundSqlDataSource(){if(this.globalTransaction?.isActive)return this.globalTransaction.sql;if(this.clsEnabled){let e=He.getTransaction();if(e?.isActive&&e.sql.logicalSourceId===this.logicalSourceId)return e.sql}return null}async useCache(e,r,...n){if(!this.cacheAdapter)throw new S("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new S("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=o.length,a=typeof r=="number"&&s===n.length,l,u=[];a?(l=r,u=n):(l=void 0,u=r!==void 0?[r,...n]:n);let d=Hn(JSON.stringify(u)),c=d?`${e}:${d}`:e,m=await this.cacheAdapter.get(c);if(m!==void 0)return m;let p=await o(...u);return await this.cacheAdapter.set(c,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new S("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(n.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Hn(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.id=this.id,r.logicalSourceId=this.logicalSourceId,r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.driverAdapter=await Dn(r.sqlType,this.inputDetails),r.sqlPool=r.driverAdapter.pool,r.ownsPool=true):(r.driverAdapter=this.driverAdapter,r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let n=this.getTransactionBoundSqlDataSource()??this;if(typeof e=="string"){let o=new B(zl(e,r),n);return r?.alias&&o.table(e,r.alias),o}return new ot(e,n)}fromRaw(e,r=[],n){let o=this.getTransactionBoundSqlDataSource()??this;return new B(zl("",n),o).fromRaw(e,r)}schema(){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Wt(this,this.getDbType())}async startGlobalTransaction(e){for(;this.globalTransactionLock;)await this.globalTransactionLock;if(this.globalTransaction?.isActive)throw new S("SqlDataSource::startGlobalTransaction","GLOBAL_TRANSACTION_ALREADY_STARTED");let r=()=>{};this.globalTransactionLock=new Promise(n=>{r=n;});try{let n=await this.clone();return n.sqlConnection=await n.getConnection(),this.globalTransaction=new tr(n,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}finally{r(),this.globalTransactionLock=null;}}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new S("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");try{await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}try{await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async transaction(e,r){let n=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let o=this.clsEnabled?He.getTransaction():void 0;if(o?.isActive&&o.sql.logicalSourceId===this.logicalSourceId)return typeof e=="function"?o.nestedTransaction(e):o.nestedTransaction();let s=await this.clone();s.sqlConnection=await s.getConnection();let a=new tr(s,n?.isolationLevel);if(await a.transaction(),typeof e=="function")try{let l=this.clsEnabled?await He.run(a,()=>e(a)):await e(a);return await a.commit({throwErrorOnInactiveTransaction:!1}),l}catch(l){throw await a.rollback({throwErrorOnInactiveTransaction:false}),l}return a}getModelManager(e){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");let r=this.getTransactionBoundSqlDataSource()??this;return new st(e,r)}getPool(){if(!this.sqlPool)throw this.lazyLoad?new S("SqlDataSource::getPool - call ensureConnected() or connect() first when using lazyLoad","CONNECTION_NOT_ESTABLISHED"):new S("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;await this.ensureConnected();let e=this.driverAdapter;if(!e)throw new S("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");return e.reserveConnection()}async disconnect(){if(!this.isConnected){g.warn("Connection already closed or not established");return}if(!this.ownsPool){if(this.sqlConnection)try{this.driverAdapter?.releaseConnection(this.sqlConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing borrowed connection failed: ${e?.message??e}`);}this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}if(this.lockConnection){try{this.driverAdapter?.releaseConnection(this.lockConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing lock connection failed: ${e?.message??e}`);}this.lockConnection=null,this.lockKeyToId.clear();}await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),g.warn("Closing connection"),await this.driverAdapter?.closePool(),this.sqlPool=null,this.driverAdapter=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,jsEnvironment:this.inputDetails.jsEnvironment,driver:this.inputDetails.driver}}async introspectSchema(){let e=this.getDbType(),r;e==="postgres"||e==="cockroachdb"?r=`
259
+ `)}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"}async hasTable(t){return this.dataSource.hasTable(t)}async hasColumn(t,e){return this.dataSource.hasColumn(t,e)}async hasColumns(t,...e){return this.dataSource.hasColumns(t,...e)}async hasIndex(t,e){return this.dataSource.hasIndex(t,e)}async hasPrimaryKey(t){return this.dataSource.hasPrimaryKey(t)}async hasUnique(t,e){return this.dataSource.hasUnique(t,e)}async hasForeignKey(t,e){return this.dataSource.hasForeignKey(t,e)}async hasCheckConstraint(t,e){return this.dataSource.hasCheckConstraint(t,e)}async getTables(){return this.dataSource.getTables()}async getColumnListing(t){return this.dataSource.getColumnListing(t)}dropTableIfExists(t){return this.schema.dropTable(t,true),this}async dropIndexIfExists(t,e){if(await this.dataSource.hasIndex(e,t)){let n=new ce(this.dataSource.getDbType());n.dropIndex(t,e);let o=n.queryStatements[0];o&&await this.dataSource.rawQuery(o);}}renameColumn(t,e,r){return this.schema.alterTable(t,n=>{n.renameColumn(e,r);}),this}};Hr=new WeakSet,If=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 Oe=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var zr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}buildDropDependencies(t){let e=new Map,r=new Map,n=new Map;for(let o of t.relationsToDrop||[]){let s=`${o.table}.${o.relation.name}`,a=[];if(o.relation.referencedTable&&a.push(`table.${o.relation.referencedTable}`),o.relation.referencedColumns)for(let l of o.relation.referencedColumns)a.push(`column.${o.relation.referencedTable}.${l}`);e.set(s,a);}for(let o of t.tablesToDrop||[]){let s=`table.${o.table}`,a=[];for(let l of this.models){let u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===o.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let o of t.columnsToDrop||[]){let s=`column.${o.table}.${o.column}`,a=[],l=this.models.find(u=>u.table===o.table);if(l){let u=l.getColumns().find(d=>d.databaseName===o.column);if(u){u.isPrimary&&a.push(`pk.${o.table}`);let d=l.getRelations();for(let c of d)c.columnName===u.columnName&&a.push(`fk.${o.table}.${c.constraintName}`);}}n.set(s,a);}return {foreignKeys:e,tables:r,constraints:n}}topologicalSortReverse(t,e){let r=new Set,n=new Set,o=[],s=a=>{if(n.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;n.add(a);let l=e(a);for(let u of l)s(u);n.delete(a),r.add(a),o.push(a);};for(let a of t.keys())r.has(a)||s(a);return o}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],n=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of n){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 o=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 o){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 n=[],o=this.models.find(s=>s.table===r.table);if(o){let s=o.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&n.push(`PRIMARY KEY on ${r.table}`);let a=o.getRelations();for(let l of a)l.columnName===s.columnName&&n.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,n);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let n=this.models.find(o=>o.table===r.table);n&&n.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,n=>{n.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 Fl=i=>String(i??"").replace(/::[a-z_ ]+$/i,"").replace(/[()\s]/g,"").toLowerCase(),Rh=/^(current[ _]?timestamp\d*|now\d*|getdate\d*|localtimestamp\d*|localtime\d*)$/,_h={postgres:i=>i.includes("nextval"),cockroachdb:i=>i.includes("unique_rowid")},Mh={postgres:["gen_random_uuid"],cockroachdb:["gen_random_uuid"],mysql:["uuid"],mariadb:["uuid"],mssql:["newid"],sqlite:["lower(hex(randomblob(16)))"]},Ef=(i,t)=>(Mh[i]??[]).includes(Fl(t)),Rt=(i,t)=>!!i.autoCreate&&Rh.test(Fl(t)),_t=(i,t,e)=>{if(t.type!=="increment"&&t.type!=="bigIncrement")return false;let r=_h[i];return r?r(Fl(e)):false};var Gr=class Gr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new zr(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,n=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),o=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...n].filter(l=>o.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 n=this.sql.schema().createTable(r.table,o=>{for(let s of r.columns){if(Array.isArray(s.type)){o.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,o,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:[n]});}for(let r of t.columnsToAdd){let n=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:n});}return e}generateConstraintCreationOperations(t){let e=[];for(let n of t.uniquesToDrop||[]){let o=this.sql.schema().alterTable(n.table,s=>{s.dropConstraint(n.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:o});}let r=new Set((t.uniquesToDrop||[]).map(n=>n.name));for(let n of t.indexesToDrop){if(r.has(n.index))continue;let o=new ce(this.sql.getDbType());o.dropIndex(n.index,n.table);let s=o.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[s]});}for(let n of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===n.table)?.getColumns().find(u=>u.columnName===n.columns[0])?.primaryKeyConstraintName||qe(n.table,n.columns[0]),l=this.sql.schema().alterTable(n.table,u=>{let d=a||qe(n.table,n.columns[0]);u.addConstraint("primary_key",{columns:[n.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:a,data:n,dependencies:[`table.${n.table}`],sqlStatements:l});}for(let n of t.relationsToAdd){if(n.relation.type==="manyToMany")continue;let o=this.generateAddRelationViaAlter(n),s=this.computeFkConstraintName(n);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:s,data:n,dependencies:this.getForeignKeyDependencies(n),sqlStatements:o});}for(let n of t.uniquesToAdd||[]){let o=this.models.find(l=>l.table===n.table),s=(n.columns||[]).map(l=>o?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(n.table,l=>{l.addConstraint("unique",{columns:s,constraintName:n.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name||"mandatory",data:n,dependencies:[`table.${n.table}`],sqlStatements:a});}for(let n of t.indexesToAdd){let o=this.generateCreateIndexSql(n);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[o]});}for(let n of t.checksToDrop||[]){let o=new ce(this.sql.getDbType());o.dropCheck(n.table,n.name);let s=o.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}for(let n of t.checksToAdd||[]){let o=new ce(this.sql.getDbType());o.addCheck(n.table,n.expression,{constraintName:n.name});let s=o.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=C(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=C(t.relation.manyToManyOptions.throughModel));let o=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=o.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=o.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 n=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:n});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let n=t.relation.model();e.push(`table.${n.table}`);let o=n.primaryKey||"id",s=n.getColumns().find(a=>a.columnName===o);s&&e.push(`column.${n.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let n=C(t.relation.manyToManyOptions.throughModel);e.push(`table.${n}`);}e.push(`table.${t.table}`);let r=this.models.find(n=>n.table===t.table);if(r){let n=r.getColumns().find(o=>o.columnName===t.relation.columnName||o.databaseName===t.relation.columnName);n&&e.push(`column.${t.table}.${n.databaseName}`);}return e}applyNullableConstraint(t,e){return e===false?t.notNullable():e===true||this.sql.getDbType()==="mariadb"?t.nullable():t}executeBuilderMethod(t,e,r,n,o=true){let s;if(Array.isArray(r.type))s=e.enum(n[0],r.type);else if(typeof r.type=="string"&&Gr.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...n);else if(typeof r.type=="string")s=e.custom(n[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return o&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||qe(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),this.applyNullableConstraint(s,r.constraints?.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(n=>{let o=this.executeBuilderMethod(t.table,n,t.column,e,false);return t.column.constraints?.default!==void 0&&o.default(t.column.constraints.default),this.applyNullableConstraint(o,t.column.constraints?.nullable),o});}).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,n=>{n.alterColumn(o=>{let s=this.executeBuilderMethod(t.table,o,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&!Rt(t.modelColumn,t.dbColumns.defaultValue)&&!_t(this.sql.getDbType(),t.modelColumn,t.dbColumns.defaultValue)&&s.default(null),this.applyNullableConstraint(s,t.modelColumn.constraints?.nullable),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),n=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),o=new ce(this.sql.getDbType());return o.createIndex(t.table,n,{constraintName:t.index}),o.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=C(t.relation.manyToManyOptions.throughModel),r=C(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let n=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,o=C(r);if(t.relation.type==="belongsTo"){let m=t.relation.model(),p=m.primaryKey,f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=z(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.model();if(typeof o=="string"&&o){let p=m.getColumns(),h=p.find(f=>f.columnName===o);if(h)o=h.databaseName;else {let f=m.primaryKey||"id",T=p.find(w=>w.columnName===f);if(T)o=T.databaseName;else {let w=m?.databaseCaseConvention||"preserve";o=z(o||f,w);}}}else {let p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=z(p,T);}}}let s=this.models.find(m=>m.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(m=>m.columnName===l);if(u)l=u.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=z(l,m);}if(t.relation.type==="belongsTo"){let m=a.find(p=>p.columnName===t.relation.foreignKey);if(m)l=m.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=z(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.manyToManyOptions.leftForeignKey,p=C(m),h=a.find(f=>f.columnName===p);if(h)l=h.databaseName;else {let f=s?.databaseCaseConvention||"preserve";l=z(p,f);}}let d=t.relation.onDelete?.toLowerCase(),c=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,m=>{let p=n||Z(t.table,l,e);m.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[o]},constraintName:p,onDelete:d,onUpdate:c});}).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," "))}))}};Gr.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 jt=Gr;var Zr=class Zr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],n=null,o={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==n&&(n=s.phase,e.length>0&&e.push(""),e.push(`// ${o[n]}`));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 o of e.columns){let s=this.generateColumnCode(e.table,o,true);r.push(` ${s}`);}r.push("});");let n=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:n}}generateAddColumnCode(t){let{table:e,column:r}=t.data,n=this.generateColumnCode(e,r,false),o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:o,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:n}=t.data,o=this.generateColumnCodeForModify(e,r,n),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(n.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],o=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:n,down:o}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u),s=o.length===1?this.quote(o[0]):`[${o.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)});`],n=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:n}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:n,referencedColumn:o,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(", ")} }`:"",c=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(n)}, ${this.quote(o)}${d});`,"});"],m=s||Z(e.table,r,n),p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(m)});`,"});"];return {up:c,down:p}}generateDropForeignKeyCode(t){let e=t.constraint||t.data?.relation?.name;if(!e)return {up:null,down:null};let r=t.table||t.data?.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],o=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:n,down:o}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=`[${(e.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,n=t.constraint||e.name;if(!n||!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(n)});`,"});"],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(n)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:a,down:l}}let o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(n)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:o,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)} });`],n=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:n}}generateAddPrimaryKeyCode(t){let e=t.data,o=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||qe(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(o)} });`,"});"],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)});`],n=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:n}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],o=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:n,down:o}}generateColumnCode(t,e,r){let n=this.generateColumnTypeCode(e);if(!r)return n;if(e.isPrimary){let o=e.primaryKeyConstraintName||qe(t,e.columnName);n+=`.primaryKey({ constraintName: ${this.quote(o)} })`;}return e.unsigned&&(n+=".unsigned()"),e.zerofill&&(n+=".zerofill()"),e.constraints?.default!==void 0&&(n+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n+";"}generateColumnCodeForModify(t,e,r){let n=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?n+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&!Rt(e,r.defaultValue)&&!_t(this.sql.getDbType(),e,r.defaultValue)&&(n+=".default(null)"),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n}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)})`:Zr.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(m=>m.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=C(t.relation.manyToManyOptions.throughModel);let l=C(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let o=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=o.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=C(t.relation.manyToManyOptions.leftForeignKey);s=o.find(d=>d.columnName===l)?.databaseName||l;}else s=o.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName:C(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))}};Zr.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 Yr=Zr;function Oh(i){return i.replace(/\s+/g," ").trim()}function Dh(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ah(i){let t=i.split(/\s+/).filter(n=>n.length>0),e=[],r=[];for(let n of t)n==="unsigned"||n==="zerofill"?e.push(n):r.push(n);return {bareBase:r.join(" "),modifiers:e}}function $h(i,t){return t.length===0?i:`${i} ${t.join(" ")}`}function Ue(i,t){let e=Oh(t.toLowerCase()),r=Dh(e);switch(i){case "sqlite":{let n=[{test:o=>o==="increment",normalized:"integer"},{test:o=>o==="bigincrement",normalized:"integer"},{test:o=>o.includes("int"),normalized:"integer"},{test:o=>o==="string",normalized:"varchar"},{test:o=>o.includes("char"),normalized:"varchar"},{test:o=>o.includes("text"),normalized:"text"},{test:o=>o.includes("clob"),normalized:"text"},{test:o=>o.includes("date"),normalized:"text"},{test:o=>o.includes("time"),normalized:"text"},{test:o=>o.includes("timestamp"),normalized:"text"},{test:o=>o.includes("datetime"),normalized:"text"},{test:o=>o.includes("blob"),normalized:"blob"},{test:o=>o.includes("real")||o.includes("floa")||o.includes("doub"),normalized:"real"},{test:o=>o.includes("numeric"),normalized:"numeric"},{test:o=>o.includes("bool"),normalized:"integer"},{test:o=>o.includes("uuid"),normalized:"varchar"},{test:o=>o.includes("ulid"),normalized:"varchar"},{test:o=>o.includes("jsonb"),normalized:"text"},{test:o=>o.includes("json"),normalized:"text"}];for(let o of n)if(o.test(r))return o.normalized;return r}case "mysql":case "mariadb":{let{bareBase:n,modifiers:o}=Ah(r),a=new Set(["int","integer","increment","tinyint","smallint","mediumint","bigint","bigincrement","float","double","double precision","real","decimal","numeric","year","bool","boolean"]).has(n);if(n.endsWith("text")||n==="text")return "text";let l;switch(n){case "int":case "integer":case "increment":l="integer";break;case "tinyint":l="boolean";break;case "smallint":l="smallint";break;case "mediumint":l="mediumint";break;case "bigint":case "bigincrement":l="bigint";break;case "float":l="float";break;case "double":case "double precision":l="double";break;case "real":l="double";break;case "decimal":case "numeric":l="numeric";break;case "string":case "varchar":case "character varying":l="varchar";break;case "char":case "character":l="char";break;case "uuid":l="varchar";break;case "ulid":l="varchar";break;case "date":l="date";break;case "datetime":l="datetime";break;case "timestamp":l="timestamp";break;case "time":l="time";break;case "year":l="year";break;case "jsonb":case "json":l=i==="mariadb"?"text":"json";break;case "enum":l="enum";break;case "binary":l="binary";break;case "varbinary":l="varbinary";break;case "tinyblob":l="tinyblob";break;case "mediumblob":l="mediumblob";break;case "longblob":l="longblob";break;case "blob":l="blob";break;case "boolean":case "bool":l="boolean";break;default:l=n;break}return a&&o.length>0?$h(l,o):l}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}}default:return r}}var rt=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 n=await e.sql.getTableSchema(r.table),o={columns:r.getColumns().filter(f=>f?.type!==void 0&&f?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!n.columns.length){e.data.tablesToAdd.push({table:r.table,columns:o.columns});for(let w of o.indexes)n.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 T=r.getChecks?.()||[];for(let w of T)e.data.checksToAdd.push({table:r.table,name:w.name,expression:w.expression});for(let w of o.relations){if(w.type!=="belongsTo")continue;let q=C(w.constraintName);n.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 o.columns)n.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 n.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 o.indexes)n.indexes.map(T=>T.name).includes(f.name)||e.data.indexesToAdd.push({table:r.table,index:f.name});let a=r.getUniques?.()||[];for(let f of a)n.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=n.foreignKeys.map(f=>f.name);for(let f of n.indexes)f.isUnique||l.includes(f.name)||o.indexes.map(w=>w.name).includes(f.name)||e.data.indexesToDrop.push({table:r.table,index:f.name});for(let f of n.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)n.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)),c=o.columns.filter(f=>Array.isArray(f.type)),m=new Set(c.map(f=>f.databaseName||f.columnName));for(let f of n.checkConstraints)if(!d.has(f.name)){let T=[...m].find(w=>{let q=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),D=new RegExp(`[\\["\\[]?${q}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i"),R=new RegExp(`[\\("\\[]?${q}[\\)"\\]]?(?:::text)?\\s*=\\s*ANY\\s*\\(`,"i");return D.test(f.expression)||R.test(f.expression)});if(T){let w=c.find(D=>(D.databaseName||D.columnName)===T),q=n.columns.find(D=>D.name===T);if(w&&q?.enumValues&&Array.isArray(w.type)){let D=[...w.type].sort(),R=[...q.enumValues].sort();if(!(D.length===R.length&&D.every((A,O)=>A===R[O]))){e.data.checksToDrop.push({table:r.table,name:f.name});let A=e.sql.getDbType(),O=A==="mssql"?"[":'"',K=A==="mssql"?"]":'"',le=w.type.map(v=>`'${v.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:f.name,expression:`${O}${T}${K} IN (${le})`});}}}else e.data.checksToDrop.push({table:r.table,name:f.name});}for(let f of o.columns){let T=n.columns.find(D=>D.name===f.databaseName||D.name===f.columnName);if(!T)continue;let w=!e.areColumnsEqual(T,f,n.indexes),q=e.getDefaultChange({table:r.table,dbColumns:T,modelColumn:f});(w||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:T,modelColumn:f});}for(let f of o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;if(f.type==="manyToMany"&&f.manyToManyOptions){let q=C(f.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:C(f.manyToManyOptions.leftForeignKey),foreignKey:f.manyToManyOptions.leftForeignKey,constraintName:f.constraintName?C(f.constraintName):Z(q,C(f.manyToManyOptions.leftForeignKey||Ll(r.table)),r.table),onDelete:f.onDelete,onUpdate:f.onUpdate},onDelete:f.onDelete,onUpdate:f.onUpdate});continue}let T=C(f.constraintName);if(T&&n.foreignKeys.some(q=>q.name===T))continue;n.foreignKeys.find(q=>e.relationMatchesDbRelation(r,f,q))||e.data.relationsToAdd.push({table:r.table,relation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let p=new Set(o.relations.filter(f=>f.type==="belongsTo").map(f=>{let T=C(f.foreignKey)||f.columnName,q=r.getColumns().find(D=>D.columnName===T)?.databaseName||T;return C(f.constraintName)||Z(r.table,q,f.model().table)}));for(let f of n.foreignKeys){if(f.name&&p.has(f.name))continue;o.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 o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;let T=n.foreignKeys.find(w=>e.relationMatchesDbRelation(r,f,w));T&&!e.areRelationsEqual(T,f)&&e.data.relationsToModify.push({table:r.table,dbRelation:T,modelRelation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let h=r.primaryKey;if(h&&!n.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[h]}),n.primaryKey&&!h&&e.data.primaryKeysToDrop.push({table:r.table,columns:n.primaryKey.columns,name:n.primaryKey.name}),h&&n.primaryKey){let f=r.getColumns().find(T=>T.columnName===h);f&&!e.arePrimaryKeysEqual(n.primaryKey,f)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:n.primaryKey,modelPrimaryKey:h});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let n=r.trim();return n?!this.emptyStatements.some(o=>o.test(n)):false})}getCodeStatements(){let e=new jt(this.sql).generateOperations(this.data);return new Yr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new jt(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),n={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let o of r)n[o.phase].push(...o.sqlStatements);return n}areColumnsEqual(t,e,r=[]){let n=t.name===e.databaseName,o=this.sql.getDbType(),s=Ue(o,t.dataType),a=typeof e.type=="string"?Ue(o,e.type):void 0,l=s.split(" ").filter(d=>d!=="unsigned"&&d!=="zerofill").join(" ");if(a&&n&&(n=l===a),Array.isArray(e.type)&&(o==="mysql"||o==="mariadb")){let d=[...e.type].sort(),c=t.enumValues?[...t.enumValues].sort():null;c&&n&&(n=d.length===c.length&&d.every((m,p)=>m===c[p]));}e.length!=null&&t.length!=null&&n&&(n=t.length===e.length);let u=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(o==="postgres"||o==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&n&&(n=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,c=t.isNullable;n=n&&d===c;}if(o==="mysql"||o==="mariadb"){if(e.unsigned!==void 0){let d=e.unsigned??false,c=t.unsigned??false;n&&(n=d===c);}if(e.zerofill!==void 0){let d=e.zerofill??false,c=t.zerofill??false;n&&(n=d===c);}}if(e.stringMode!==void 0){let d=e.stringMode??false,c=t.stringMode??false;n&&(n=d===c);}return n}areRelationsEqual(t,e){let r=C(e.constraintName),n=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",c=u.getColumns().find(h=>h.columnName===d),m=u.table,p=c?.databaseName||d;n=n&&t.referencedTable===m&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=C(e.manyToManyOptions.throughModel);n=n&&t.referencedTable===u;}let o=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&n&&(n=o===a),l&&n&&(n=s===l),n}relationMatchesDbRelation(t,e,r){let n,o=e;if(o&&o.model){if(typeof o.model=="function"&&o.model.table)n=o.model;else if(typeof o.model=="function")try{let f=o.model();f&&f.table&&(n=f);}catch{}}if(!n)return false;let s=e.type==="belongsTo"?n.table:e.type==="manyToMany"&&e.manyToManyOptions?C(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=C(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),d=(o.type||"belongsTo")==="belongsTo"?C(o.foreignKey):o.columnName,c=l.find(f=>f.columnName===d);c&&(d=c.databaseName);let m=n.primaryKey||"id",h=n.getColumns().find(f=>f.columnName===m)?.databaseName||m;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let n=t.columns[0]===e.databaseName,o=this.sql.getDbType();if(["mysql","mariadb"].includes(o))return n;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return n&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Ue(e,t.dbColumns.dataType),n=typeof t.modelColumn.type=="string"?Ue(e,t.modelColumn.type):void 0;if(n&&r!==n||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"&&(n==="timestamp"||n==="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;if(s&&!a)return "set";if(!s&&a){let l=t.dbColumns.defaultValue;return _t(e,t.modelColumn,l)||Rt(t.modelColumn,l)||t.modelColumn.type==="uuid"&&Ef(e,l)?false:"drop"}if(s&&a){let l=String(t.dbColumns.defaultValue),u=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,l),c=this.normalizeDefaultValue(e,n||r,u);return d!==c?"set":false}return false}normalizeDefaultValue(t,e,r){let n=String(r).trim();if(!n)return n;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=n.match(/^'(.*)'$/s);if(s&&(n=s[1]),n==="{}"||n==="")return "{}";let a=JSON.parse(n);return JSON.stringify(a)}catch{}n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),/^true$/i.test(n)?"true":/^false$/i.test(n)?"false":/^null$/i.test(n)?"null":(n)}if(t==="mysql"||t==="mariadb"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);if(o&&(n=o[1]),/^current_timestamp(?:\(\d+\))?$/i.test(n))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(n))return "true";if(/^0$/.test(n))return "false"}return n}if(t==="sqlite"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),n.toLowerCase()}return n}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let n of r){if(n.type!=="manyToMany"||!n.manyToManyOptions||n.manyToManyOptions.wasModelProvided)continue;let o=C(n.manyToManyOptions.throughModel);if(t.has(o))continue;t.add(o);let s=this.models.find(v=>v.table===n?.manyToManyOptions?.primaryModel),a=n.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find(v=>v.columnName===l),c=a.getColumns().find(v=>v.columnName===u);if(!d||!c)continue;let m=C(n.manyToManyOptions.leftForeignKey)||l,p=C(n.manyToManyOptions.rightForeignKey)||u,h=await this.sql.getTableSchema(o);if(!h.columns.length){this.data.tablesToAdd.push({table:o,columns:[this.clonePkAsColumn(d,m),this.clonePkAsColumn(c,p)]}),this.pushM2mFkRelations({throughTable:o,leftModel:s,rightModel:a,leftFkName:m,rightFkName:p,onDelete:n.onDelete,onUpdate:n.onUpdate,constraintName:void 0});continue}let f=this.clonePkAsColumn(d,m),T=this.clonePkAsColumn(c,p),w=h.columns.find(v=>v.name===m),q=h.columns.find(v=>v.name===p),D=w?this.areColumnsEqual(w,f,h.indexes):false,R=q?this.areColumnsEqual(q,T,h.indexes):false;for(let v of h.foreignKeys){let ne=v.referencedTable===s.table,Ye=v.referencedTable===a.table;if(!ne&&!Ye)continue;let _e=ne?m:p,Me=v.columns[0];Me&&Me!==_e&&(this.data.relationsToDrop.push({table:o,relation:v}),Me!==m&&Me!==p&&this.data.columnsToDrop.push({table:o,column:Me}));}let $={};D||($[f.databaseName]=f),R||($[T.databaseName]=$[T.databaseName]||T);for(let v of Object.keys($))this.data.columnsToAdd.push({table:o,column:$[v]});let A=this.buildBelongsToRelation(o,()=>s,m,l,void 0,n.onDelete,n.onUpdate),O=this.buildBelongsToRelation(o,n.model,p,u,void 0,n.onDelete,n.onUpdate),K=h.foreignKeys.find(v=>v.referencedTable===s.table&&v.columns.length===1&&v.columns[0]===m),le=h.foreignKeys.find(v=>v.referencedTable===a.table&&v.columns.length===1&&v.columns[0]===p);if(!K){let v=h.foreignKeys.find(ne=>ne.referencedTable===s.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(A);}if(!le){let v=h.foreignKeys.find(ne=>ne.referencedTable===a.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(O);}}}}async removeFkChurnByName(){let t=new Set;for(let n of this.data.relationsToAdd)t.add(n.table);for(let n of this.data.relationsToDrop)t.add(n.table);let e=new Map;for(let n of t){let o=await this.sql.getTableSchema(n),s=new Set((o.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(n,s);}let r=new Map;for(let n of this.models){let o=n.getRelations(),s=new Set;for(let a of o){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=n.getColumns().find(m=>m.columnName===l)?.databaseName||l,c=C(a.constraintName)||Z(n.table,d,a.model().table);s.add(c);}r.set(n.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async n=>{let o=await this.sql.getTableSchema(n.table),s=this.models.find(f=>f.table===n.table),a=s?.getColumns()||[],l=n.relation.columnName;n.relation.type==="belongsTo"?l=a.find(T=>T.columnName===n.relation.foreignKey)?.databaseName||n.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let u=n.table,d=n.relation.foreignKey;if(n.relation.type==="belongsTo"){let f=n.relation.model();u=f.table;let T=f.primaryKey||"id";d=f.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let c=new Set([l,n.relation.columnName].filter(Boolean)),m=o.foreignKeys.some(f=>{if(f.columns.length!==1||f.referencedColumns.length!==1)return false;let T=c.has(f.columns[0]),w=f.referencedTable===u,q=f.referencedColumns[0]===d;return T&&w&&q}),p=C(n.relation.constraintName)||Z(n.table,l,u),h=e.get(n.table)||new Set;if(m||p&&h.has(p))return null;if(n.relation.type==="manyToMany"&&n.relation.manyToManyOptions){let f=C(n.relation.manyToManyOptions.throughModel),T=C(n.relation.manyToManyOptions.leftForeignKey),w=C(n.relation.manyToManyOptions.rightForeignKey),q=n.table===f&&n.relation.columnName===T&&n.relation.model().table===s?.table,D=n.table===f&&n.relation.columnName===w&&n.relation.model().table!==s?.table,R=await this.sql.getTableSchema(f),$=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===T&&O.referencedTable===(s?.table||"")),A=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===w&&O.referencedTable===n.relation.model().table);if(q&&$||D&&A)return null}return n})).then(n=>n.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async n=>{let o=this.models.find(u=>u.table===n.table);if(!o)return n;let s=o.getRelations(),a=o.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let c=a.find(T=>T.columnName===u.foreignKey)?.databaseName||u.foreignKey,m=u.model(),p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p)?.databaseName||p;return n.relation.columns.length===1&&n.relation.columns[0]===c&&n.relation.referencedTable===m.table&&n.relation.referencedColumns.length===1&&n.relation.referencedColumns[0]===f})?null:n})).then(n=>n.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,n,o,s,a){let l=o?C(o):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 Ve=class{};Ve.modelCaseConvention="camel",Ve.databaseCaseConvention="snake";var Bf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");return o+=n.final("hex"),`${r.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},kf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=String(t).trim(),[n,o]=r.split(":");if(!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=n.toLowerCase(),a=o.toLowerCase(),l=Pe.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 S("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Kf=(i,t)=>{try{let e=Pe.randomBytes(32),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");o+=n.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Qf=(i,t)=>{try{let e=String(t).trim(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=privateDecrypt(i,Buffer.from(n,"hex")),a=Pe.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(o,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new S("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var G=class{static defineMetadata(t,e,r,n){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let o=this.store.get(r);o||(o=new Map,this.store.set(r,o));let s=o.get(n);s||(s=new Map,o.set(n,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 n=e;for(;n;){let o=this.store.get(n);if(o){let s=o.get(r);if(s&&s.has(t))return s.get(t)}n=Object.getPrototypeOf(n);}}};G.store=new WeakMap;var Vl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ul=Vl.length,Ph=10,Eh=16,Bh=(i,t)=>{let e="";for(let r=0;r<t;r++){let n=i%Ul;e=Vl.charAt(n)+e,i=(i-n)/Ul;}return e},kh=i=>{let t=ie().crypto.randomBytes(i),e="";for(let r=0;r<i;r++){let n=t[r];e+=Vl.charAt(n%Ul);}return e},Lf=()=>{let i=Math.floor(Date.now()/1e3),t=Bh(i,Ph),e=kh(Eh);return t+e};var Xr=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var en=class extends Oe{constructor(e,r,n){super(e,r);this.type="hasMany";this.foreignKey=n,this.type="hasMany";}};var tn=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var rn=class extends Oe{constructor(e,r,n){super(e,r);this.type="manyToMany";this.primaryModel=n.primaryModel,this.relatedModel=e.table,this.throughModel=n.throughModel,this.leftForeignKey=n.leftForeignKey,this.rightForeignKey=n.rightForeignKey;}};function _(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let n=e.constructor;if(t){if(G.getMetadata(Ct,e))throw new S("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");G.defineMetadata(Ct,r,e),G.defineMetadata(Ct,r,e.constructor);}let o=i.databaseName??z(r,n.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??qe(n.table,r),autoUpdate:i.autoUpdate,autoCreate:i.autoCreate,databaseName:o,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,unsigned:i.unsigned,zerofill:i.zerofill,stringMode:i.stringMode,expression:i.expression,constraints:{nullable:i.nullable,default:i.default}};s.validate=i.validate;let a=G.getMetadata(jr,e)||[];a.push(s),G.defineMetadata(jr,a,e);}}_.primary=Kh;_.date=tg;_.datetime=rg;_.timestamp=ng;_.time=og;_.boolean=eg;_.json=sg;_.uuid=Fh;_.ulid=Uh;_.integer=Lh;_.bigInteger=Hh;_.float=Qh;_.decimal=zh;_.increment=Wh;_.bigIncrement=jh;_.string=Vh;_.text=Jh;_.binary=Gh;_.enum=Yh;_.encryption={symmetric:Zh,asymmetric:Xh};_.computed=ig;function Kh(i={}){return _({...i,primaryKey:true})}function Qh(i={}){return _({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 Lh(i={}){return _({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function Wh(i={}){return _({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 jh(i={}){return _({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 Fh(i={}){return _({type:"uuid",...i,prepare:t=>t||ie().crypto.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function Uh(i={}){return _({type:"ulid",...i,prepare:t=>t||Lf(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Vh(i={}){return _({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Jh(i={}){return _({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Hh(i={}){return _({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 zh(i={}){return _({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 Gh(i={}){return _({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Yh(i,t={}){return _({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Zh(i){return _({...i,prepare:t=>t&&Bf(i.key,t),serialize:t=>t&&kf(i.key,t)})}function Xh(i){return _({...i,prepare:t=>t&&Kf(i.publicKey,t),serialize:t=>t&&Qf(i.privateKey,t)})}function eg(i={}){return _({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function tg(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"DATE_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"date",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"DATE_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...o.openApi||{}}})}function rg(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"ISO",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"datetime",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"ISO",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function ng(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"TIMESTAMP",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"timestamp",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"TIMESTAMP",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function og(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"TIME_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"time",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"TIME_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},stringMode:t,openApi:{type:"string",format:"time",description:"HH:mm:ss",...o.openApi||{}}})}function sg(i={}){return _({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 ig(i,t={}){return _({...t,expression:i})}function Wf(i){try{return G.getMetadata(jr,i.prototype)||[]}catch{return []}}function jf(i){return G.getMetadata(Ql,i.prototype)||[]}function Ff(i){return (G.getMetadata(Ql,i.prototype)||[]).map(e=>{let{type:r,model:n,columnName:o,foreignKey:s}=e,a=C(s),l=n();switch(r){case "belongsTo":return new Xr(l,o,a);case "hasOne":return new tn(l,o,a);case "hasMany":return new en(l,o,a);case "manyToMany":if(!e.manyToManyOptions)throw new S("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=n();return new rn(u,o,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:C(e.manyToManyOptions.throughModel),leftForeignKey:C(e.manyToManyOptions.leftForeignKey),rightForeignKey:C(e.manyToManyOptions.rightForeignKey)});default:throw new S("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Uf(i){return G.getMetadata(Ct,i)||G.getMetadata(Ct,i.prototype)}function Vf(i){return G.getMetadata(Mf,i.prototype)||[]}function Jf(i){return G.getMetadata(xf,i.prototype)||[]}function Hf(i){return G.getMetadata(Of,i.prototype)||[]}var ye=class{};ye.columns=new WeakMap,ye.byName=new WeakMap,ye.byDatabaseName=new WeakMap;var Ae=class extends Ve{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 Uf(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=ye.columns.get(this);return t||(t=Wf(this),ye.columns.set(this,t)),t}static getColumnsByName(){let t=ye.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),ye.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=ye.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),ye.byDatabaseName.set(this,t)),t}static getRelations(){return jf(this)}static getIndexes(){return Vf(this)}static getUniques(){return Jf(this)}static getChecks(){return Hf(this)}static async validate(t){var s,a;let e=this.getColumns(),r={},n=this.primaryKey,o=n&&t?.[n]!==void 0?"update":"insert";for(let l of e){if(l.expression)continue;let u=l.validate;if(!u)continue;let d=t?t[l.columnName]:void 0,c=Array.isArray(u)?u:[u];for(let m of c)try{let p=await m(d,{model:this,column:l.columnName,operation:o,data:t});if(!(p&&p.valid)){let h=p&&p.message||"Validation failed";(r[s=l.columnName]||(r[s]=[])).push(h);}}catch{(r[a=l.columnName]||(r[a]=[])).push("Validation error");}}if(Object.keys(r).length>0)throw new Pt(r);return {valid:true}}};Ae.zodEngine=null,Ae.softDeleteColumn="deletedAt",Ae.softDeleteValue=bt();var Mt=class extends N{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};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 re=class extends N{constructor(e,r=[],n,o=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=n,this.disableReturning=o;}};var Ce=class extends N{constructor(e,r,n,o="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=n,this.mode=o,this.returning=s;}};var xt=class extends N{constructor(e=[],r="inserted"){super("returning");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="returning";this.file="returning";this.columns=e,this.prefix=r;}};var Ee=class extends N{constructor(e,r=[],n=[],o=false){super("update",o);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=n;}};var M=class extends N{constructor(e,r,n=false,o,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=n,this.operator=o,this.value=s;}};var $e=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 j=class extends M{constructor(e,r,n=false,o,s,a=false,l,u){super(e,r,n,"=",s,a);this.file="where_json";this.jsonOperator=o,this.value=s,this.path=l,this.comparisonOperator=u;}};var Re=class extends N{constructor(e,r,n,o="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=n,this.chainsWith=` ${o}`;}};var zf;zf=Symbol.toStringTag;var Y=class{constructor(t,e,r,n){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=n;this[zf]="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 ag=(i,t,e,r,n,o=false,s=new Set)=>{let a=Object.create(t.prototype);for(let l of Object.keys(i)){let u=i[l],d=s.has(l),c=e.get(l),m=l;!c&&!d&&(c=r.get(l),c&&(m=c.columnName));let p=c!==void 0,h=d||o?true:n?n.has(m):true;if(p){if(!h)continue;if(u===null){a[m]=null;continue}if(c?.serialize){let f=c.serialize(u);if(f!==null&&typeof f?.then=="function")throw new Error(`hysteria-orm: column "${m}" on model "${t.name}" has an async serialize function, but serializers must be synchronous. Move async work to prepare or a getter.`);a[m]=f;continue}a[m]=u;continue}(d||!o||n&&n.has(m))&&(a[m]=u);}if(n)for(let l of n)l in a||(a[l]=null);return a},he=(i,t,e=[],r=[])=>{if(!i.length)return null;let n=t.getColumnsByName(),o=t.getColumnsByDatabaseName(),s=e.some(c=>c.includes("*")),a=[];for(let c of e){if(c.toLowerCase().includes(" as ")){let f=c.match(/\s+as\s+(.+)$/i);f&&a.push(f[1].trim());continue}let p=c;if(p.includes(".")&&(p=p.split(".").pop()),p==="*")continue;let h=n.get(p)?.columnName??p;a.push(h);}let l=a.length?new Set(a):null,u=new Set(r),d=i.map(c=>ag(c,t,n,o,l,s,u));return d.length===1?d[0]:d};var Ft=class{constructor(t){this.observers=t??[];}add(t){this.observers.push(t);}async notifyBefore(t){for(let e of this.observers)e?.onBeforeQuery&&await e.onBeforeQuery(t);}async notifyAfter(t,e){for(let r of this.observers)r?.onAfterQuery&&(t.result??(t.result=e),await r.onAfterQuery(t));}async notifyError(t){for(let e of this.observers)e?.onQueryError&&await e.onQueryError(t);}},Gf=i=>{if(!i)return "OTHER";let t=i.trim().toUpperCase();return t.startsWith("SELECT")?"SELECT":t.startsWith("INSERT")?"INSERT":t.startsWith("UPDATE")?"UPDATE":t.startsWith("DELETE")?"DELETE":"OTHER"};var nn=ie();function Jl(i){let t=nn.timing.now()-i;return Math.round(t*100)/100}var J=async(i,t,e,r,n="rows",o)=>{await e.ensureConnected();let s={id:nn.crypto.randomUUID(),sql:i,params:t,model:void 0,operation:Gf(i),timestamp:nn.timing.now()};try{let u=e.observerChain;u&&typeof u.notifyBefore=="function"&&await u.notifyBefore(s);}catch{}let a=nn.timing.now(),l=u=>{o?.shouldNotLog||ct(i,e.logs,t,e.inputDetails.queryFormatOptions,r,u);};try{let u=e.driverAdapter;if(!u)throw new S("ExecSql","CONNECTION_NOT_ESTABLISHED");let d=o?.timeout,c=d?new AbortController:void 0,m,p=lg(()=>u.execute(i,t,{returning:n,sqlLiteOptions:o?.sqlLiteOptions,signal:c?.signal,connection:e.sqlConnection}),e.inputDetails.connectionPolicies?.retry,e.logs),h;try{d&&c?(h=await Promise.race([p,new Promise((f,T)=>{m=setTimeout(()=>{let w=new S("ExecSql::timeout","QUERY_TIMEOUT",new Error(`Query exceeded the ${d.ms}ms timeout`));d.cancel&&c.abort(w),T(w);},d.ms);})]),p.catch(()=>{})):h=await p;}finally{m&&clearTimeout(m);}try{let f=Jl(a),T=e.observerChain;if(T&&typeof T.notifyAfter=="function"){let w={...s,duration:f,result:h};await T.notifyAfter(w);}}catch{}return l(Jl(a)),u.extract(h,n)}catch(u){throw l(Jl(a)),u}},on=async(i,t,e,r={},n)=>{let o=e.driverAdapter;if(!o)throw new S("ExecSqlStreaming","CONNECTION_NOT_ESTABLISHED");return await o.stream(i,t,{...r,connection:e.sqlConnection??void 0},{onData:n.onData})};async function lg(i,t={maxRetries:0,delay:0},e=false){let r=0,n=t.maxRetries||0,o=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<n)return r++,Nu(`Retrying sql in ${o}ms (attempt ${r}/${n})`,"info",e),await new Promise(l=>setTimeout(l,o)),s();throw a}}return s()}var H=class extends N{constructor(e,r,n,o,s){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=n,this.isRawValue=o??false,this.distinct=s;}};var Ut=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Ff(t),this.modelRelationsMap=new Map(this.modelRelations.map(n=>[n.columnName,n]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new S("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function sn(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}}var Ot=i=>typeof i=="number"?i:parseFloat(i);var X=class extends N{constructor(e,r,n=false,o,s,a=false,l,u){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=` ${r}`,this.isNegated=n,this.operator=o,this.value=s,this.subquery=l,this.group=u;}};var an=class extends N{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var ln=class extends N{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Je=class extends N{constructor(e,r,n,o="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=n,this.jsonOperator=o,this.isRawValue=s;}};var se=class extends N{constructor(e,r,n,o="inner",s,a=false,l){super(`${o} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=n,this.type=o,this.on=s,this.additionalConditions=l;}};var Vt=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 un=class extends N{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var dn=class extends N{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Jt=class extends N{constructor(e,r="asc",n=false){super("order by",n);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var mn=class mn{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=mn.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 Vt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Vt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Jt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Jt(t,"asc",true)),this}limit(t){return typeof t!="number"&&g.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new un(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new dn(t),this}};mn.EMPTY_MAP=new Map;var cn=mn;var nt=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 n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",false,n,o)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",false,n,o)),this}whereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}andWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}orWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",true,n,o)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new M(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new M(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 M(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new M(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 M(t,"and",false,"in",e)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",false,"in",e)),this):(this.whereNodes.push(new M("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"and",true,"in",e)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",true,"in",e)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new M(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new M(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new M(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new M(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 M(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 M(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 M(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 M(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 $e(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 $e(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new M(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new M(t,"or",true,"=",e??[],true)),this}};var pn=class extends cn{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}crossJoin(t,e){let r=typeof t=="string"?t:t.table;return this.joinNodes.push(new se(e?`${r} as ${e}`:r,"","","cross",{operator:"="})),this}using(...t){let e=this.joinNodes[this.joinNodes.length-1];if(!e||!t.length||e.isRawValue||e.type==="cross"||e.type==="natural")throw new S("JoinQueryBuilder::using","USING_REQUIRES_JOIN");return e.using=t.map(r=>String(r)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,n,o){if(e===void 0)return this.join(typeof t=="string"?t:t.table);let s=r,a=n,l=typeof n=="function"?n:o;if(!s){if(!this.model.primaryKey)throw new S("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,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","inner",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","left",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","right",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,n,o){let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var ug=/\bas\s+"?([A-Za-z_][A-Za-z0-9_]*)"?\s*(?:,|$)/gi,dg=/^[A-Za-z_][A-Za-z0-9_.]*$/,cg=i=>{let t=[];for(let e of i.matchAll(ug))t.push(e[1]);if(!t.length){let e=i.trim();dg.test(e)&&t.push(e.split(".").pop());}return t},fn=class extends pn{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.userOutputColumns=[];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[a,l]=r;this.modelSelectedColumns.push(l),this.userOutputColumns.push(l);let u=this.resolveComputedColumn(a);if(u){this.selectNodes.push(new H(`(${u.expression}) as ${l}`,void 0,void 0,true));return}let d=z(a,this.model.databaseCaseConvention);this.selectNodes.push(new H(d,l));return}let n=r;this.modelSelectedColumns.push(n);let o=this.resolveComputedColumn(n);if(o){this.selectNodes.push(new H(`(${o.expression}) as ${o.alias}`,void 0,void 0,true));return}let s=z(n,this.model.databaseCaseConvention);this.selectNodes.push(new H(s));}),this}selectRaw(e){return this.selectNodes.push(new H(e,void 0,void 0,true)),this.userOutputColumns.push(...cg(e)),this}collectUserOutputNames(){let e=new Set(this.userOutputColumns);for(let r of this.selectNodes)r.alias&&e.add(r.alias);return [...e]}selectFunc(e,r,n){return this.selectNodes.push(new H(r,n,e)),this}countDistinct(e,r){return this.selectNodes.push(new H(e,r,"count",false,true)),this}sumDistinct(e,r){return this.selectNodes.push(new H(e,r,"sum",false,true)),this}avgDistinct(e,r){return this.selectNodes.push(new H(e,r,"avg",false,true)),this}rank(e,r={}){return this.pushWindow("rank",e,r)}denseRank(e,r={}){return this.pushWindow("dense_rank",e,r)}rowNumber(e,r={}){return this.pushWindow("row_number",e,r)}pushWindow(e,r,n){return this.selectNodes.push(new H(new Fr(e,Df(n.partitionBy),Af(n.orderBy)),r)),this}clearSelect(){return this.modelSelectedColumns=[],this.userOutputColumns=[],this.selectNodes=[],this}resolveComputedColumn(e){let r=this.model.getColumnsByName?.();if(!r||r.size===0)return;let n=e.includes(".")?e.split(".").pop():e,o=r.get(n);if(o?.expression)return {expression:o.expression,alias:o.databaseName||n}}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 an,this}distinctOn(...e){return this.distinctOnNode=new ln(e),this}selectJson(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract")),this}selectJsonText(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract_text")),this}selectJsonArrayLength(e,r,n){return this.selectNodes.push(new Je(e,r,n,"array_length")),this}selectJsonKeys(e,r,n){return this.selectNodes.push(new Je(e,r,n,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Je(e,"",r,"raw",true)),this}};var yn=class extends fn{constructor(e,r,n=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=n;}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,n){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&n===void 0?this.andWhereSubQuery(e,"in",r):r instanceof B&&n===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function")?this.andWhereSubQuery(e,r,n):this.andWhere(e,r,n)}andWhere(e,r,n){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",false,o,s)),this}orWhere(e,r,n){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",false,o,s)),this}whereColumn(e,r,n){return this.andWhereColumn(e,r,n)}andWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"and",false,o,new x(s))),this}orWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"or",false,o,new x(s))),this}whereNotColumn(e,r,n){return this.andWhereNotColumn(e,r,n)}andWhereNotColumn(e,r,n){return this.pushNotColumnWhere("and",e,r,n)}orWhereNotColumn(e,r,n){return this.pushNotColumnWhere("or",e,r,n)}pushNotColumnWhere(e,r,n,o){let s="!=",a=false,l;return o!==void 0?(s=n,l=o,a=true):l=n,this.whereNodes.push(new M(r,e,a,s,new x(l))),this}whereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}andWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}orWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",true,o,s)),this}whereBetween(e,r,n){return this.andWhereBetween(e,r,n)}andWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"and",false,"between",[r,n])),this}orWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"or",false,"between",[r,n])),this}whereNotBetween(e,r,n){return this.andWhereNotBetween(e,r,n)}andWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"and",true,"between",[r,n])),this}orWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"or",true,"between",[r,n])),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 M(e,"and",false,"in",r)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",false,"in",r)),this):(this.whereNodes.push(new M("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 M(e,"and",true,"in",r)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",true,"in",r)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new M(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new M(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new M(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new M(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"and",false,n?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"or",false,n?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"or",true,n?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"or",false,"=",r,true)),this}having(e,r,n){return this.andHaving(e,r,n)}andHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"and",false,o,s)),this}orHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"or",false,o,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new X(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new X(e,"or",false,"=",[],true)),this}havingNull(e){return this.andHavingNull(e)}andHavingNull(e){return this.havingNodes.push(new X(e,"and",false,"is null",void 0)),this}orHavingNull(e){return this.havingNodes.push(new X(e,"or",false,"is null",void 0)),this}havingNotNull(e){return this.andHavingNotNull(e)}andHavingNotNull(e){return this.havingNodes.push(new X(e,"and",false,"is not null",void 0)),this}orHavingNotNull(e){return this.havingNodes.push(new X(e,"or",false,"is not null",void 0)),this}havingIn(e,r){return this.andHavingIn(e,r)}andHavingIn(e,r){return this.pushHavingIn("and",e,r,false)}orHavingIn(e,r){return this.pushHavingIn("or",e,r,false)}havingNotIn(e,r){return this.andHavingNotIn(e,r)}andHavingNotIn(e,r){return this.pushHavingIn("and",e,r,true)}orHavingNotIn(e,r){return this.pushHavingIn("or",e,r,true)}havingBetween(e,r){return this.andHavingBetween(e,r)}andHavingBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"between",r)),this}orHavingBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"between",r)),this}havingNotBetween(e,r){return this.andHavingNotBetween(e,r)}andHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"not between",r)),this}orHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"not between",r)),this}havingExists(e){return this.andHavingExists(e)}andHavingExists(e){return this.pushHavingExists("and",e,false)}orHavingExists(e){return this.pushHavingExists("or",e,false)}havingNotExists(e){return this.andHavingNotExists(e)}andHavingNotExists(e){return this.pushHavingExists("and",e,true)}orHavingNotExists(e){return this.pushHavingExists("or",e,true)}havingWrapped(e){return this.andHavingWrapped(e)}andHavingWrapped(e){return this.pushHavingGroup("and",e)}orHavingWrapped(e){return this.pushHavingGroup("or",e)}pushHavingIn(e,r,n,o){let s=o?"not in":"in";if(Array.isArray(n))return this.havingNodes.push(new X(r,e,false,s,n)),this;let a=this.buildSubQuery(n);return this.havingNodes.push(new X(r,e,false,s,[],false,a.extractQueryNodes())),this}pushHavingExists(e,r,n){let o=r instanceof B?r:new B(this.model,this.sqlDataSource);return o.isNestedCondition=true,typeof r=="function"&&r(o),this.havingNodes.push(new X("",e,false,n?"not exists":"exists",[],false,o.extractQueryNodes())),this}pushHavingGroup(e,r){let n=new B(this.model,this.sqlDataSource);return n.isNestedCondition=true,r(n),this.havingNodes.push(new X("",e,false,"=",[],false,void 0,n.havingNodes)),this}buildSubQuery(e){if(e instanceof B)return e;let r=new B(this.model,this.sqlDataSource),n=e(r);return n!=null&&"extractQueryNodes"in n?n:r}andWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"and");return this.whereNodes.push(n),this}orWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"or");return this.whereNodes.push(n),this}};var hn=class extends yn{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"or",false,"raw",e)),this}whereJsonObject(t,e){return this.andWhereJsonObject(t,e)}andWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"and",false,"=",e)),this}orWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"or",false,"=",e)),this}whereNotJsonObject(t,e){return this.andWhereNotJsonObject(t,e)}andWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"and",true,"=",e)),this}orWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"or",true,"=",e)),this}whereJsonPath(t,e,r,n){return this.andWhereJsonPath(t,e,r,n)}andWhereJsonPath(t,e,r,n){return this.pushJsonPath("and",t,e,r,n,false),this}orWhereJsonPath(t,e,r,n){return this.pushJsonPath("or",t,e,r,n,false),this}whereJsonSupersetOf(t,e){return this.andWhereJsonSupersetOf(t,e)}andWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotSupersetOf(t,e){return this.andWhereJsonNotSupersetOf(t,e)}andWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"contains",e)),this}orWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"contains",e)),this}whereJsonSubsetOf(t,e){return this.andWhereJsonSubsetOf(t,e)}andWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"subset",e)),this}orWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"subset",e)),this}whereJsonNotSubsetOf(t,e){return this.andWhereJsonNotSubsetOf(t,e)}andWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"subset",e)),this}orWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"subset",e)),this}whereJsonHasNone(t,e){return this.andWhereJsonHasNone(t,e)}andWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"and",false,"has none",e)),this}orWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"or",false,"has none",e)),this}pushJsonPath(t,e,r,n,o,s){let a=new j(e,t,s,"path",o,false,r,n);this.whereNodes.push(a);}};var B=class i extends hn{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.returningNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.comments=[],this.hints=[],this.astParser=new b(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,n]=e;if(typeof r=="function"){let o=new i(this.model,this.sqlDataSource),s=r(o),a=s!=null&&"extractQueryNodes"in s?s:o;return this.selectNodes.push(new H(a.extractQueryNodes(),n)),this}return this.selectNodes.push(new H(r.extractQueryNodes(),n)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}countDistinct(e,r){return super.countDistinct(e,r),this}sumDistinct(e,r){return super.sumDistinct(e,r),this}avgDistinct(e,r){return super.avgDistinct(e,r),this}rank(e,r){return super.rank(e,r),this}denseRank(e,r){return super.denseRank(e,r),this}rowNumber(e,r){return super.rowNumber(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",n=>J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout,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(n=>n[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 S("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:n}=this.unWrap();return this.execSqlWithSlaveHandling("read",async o=>await on(r,n,o,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;r+=n.length,yield n;}}async paginateWithCursor(e,r){if(!this.orderByNodes.length)throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_REQUIRED");let n=this.orderByNodes;if(n.some(m=>m.isRawValue))throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_RAW_NOT_SUPPORTED");let o=n.map(m=>m.column),s=n[0].direction==="desc"?"<":">";if(r){let m=Array.isArray(r.value)?r.value:[r.value];this.andWhere(p=>{for(let h=0;h<o.length;h++){let f=h;p.orWhere(T=>{for(let w=0;w<f;w++)T.where(o[w],"=",m[w]);T.where(o[f],s,m[f]);});}});}this.limit(e+1);let a=await this.many(),l=a.length>e,u=l?a.slice(0,e):a,d=u[u.length-1],c=o.map(m=>m.includes(".")?m.slice(m.lastIndexOf(".")+1):m);return {data:u,hasMore:l,nextCursor:d?{key:c.length===1?c[0]:c,value:c.length===1?d[c[0]]:c.map(m=>d[m])}:null}}lockForUpdate(e={}){return this.lockQueryNodes.push(new Xe("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Xe("for_share",e.skipLocked,e.noWait)),this}forNoKeyUpdate(e={}){return this.assertPgLockStrength("forNoKeyUpdate","FOR NO KEY UPDATE"),this.lockQueryNodes.push(new Xe("for_no_key_update",e.skipLocked,e.noWait)),this}forKeyShare(e={}){return this.assertPgLockStrength("forKeyShare","FOR KEY SHARE"),this.lockQueryNodes.push(new Xe("for_key_share",e.skipLocked,e.noWait)),this}assertPgLockStrength(e,r){if(this.dbType!=="postgres")throw new S(`QueryBuilder::${e}`,`LOCK_STRENGTH_NOT_SUPPORTED_IN_${this.dbType.toUpperCase()}`,new Error(`${r} is only supported by postgres`))}timeout(e,r={}){return this.queryTimeout={ms:e,cancel:r.cancel??false},this}comment(e){return this.assertValidSqlComment(e),this.comments.push(e),this}hintComment(e){this.assertValidSqlComment(e);let r=e.slice(3,-2).trim(),n=this.hints[0];return this.hints=[n?`${n.slice(0,-2).trimEnd()} ${r} */`:`/*+ ${r} */`],this}clearComment(){return this.comments=[],this}clearHintComment(){return this.hints=[],this}assertValidSqlComment(e){let r=()=>{throw new S("QueryBuilder::comment","INVALID_SQL_COMMENT")};(!e.trim().length||e.includes("?"))&&r();let n=(this.dbType==="mysql"||this.dbType==="mariadb")&&e.startsWith("#");if(e.startsWith("--")||n){/[\r\n]/.test(e)&&r();return}if(e.startsWith("/*")&&e.endsWith("*/")&&e.length>=4){let o=e.slice(2,-2);(o.includes("/*")||o.includes("*/"))&&r();return}r();}union(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e,true)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n,true)),this}intersect(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"intersect")),this}except(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"except")),this}resolveSetOperationNodes(e){return typeof e=="string"?e:(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes()}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.buildCountQuery(e);let r=await this.one();return r?Ot(r.total):0}needsDerivedTableCount(){return this.groupByNodes.length>0||this.havingNodes.length>0||this.distinctNode!==null||this.distinctOnNode!==null}buildCountQuery(e="*"){if(!this.needsDerivedTableCount()){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);return}this.clearOrderBy(),this.clearLimit(),this.clearOffset();let r=this.extractQueryNodes();this.withNodes=[],this.distinctNode=null,this.distinctOnNode=null,this.clearSelect(),this.fromNode=new U(r,"g"),this.joinNodes=[],this.whereNodes=[],this.groupByNodes=[],this.havingNodes=[],this.lockQueryNodes=[],this.unionNodes=[],this.comments=[],this.hints=[],this.selectRaw(`count(${e}) as total`);}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?Ot(r.total):0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?Ot(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?Ot(r.total):0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?Ot(r.total):0}async columnInfo(e){let r=typeof this.fromNode.table=="string"?this.fromNode.table:this.model.table,o=await(await this.getSqlDataSource("read")).getTableInfo(r);return e===void 0?o:o.find(s=>s.name===e)}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new S("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let n=new i(this.model,this.sqlDataSource),o=e(n),a=(o!=null&&"extractQueryNodes"in o?o:n).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}withSchema(e){return this.schemaName=e,this}fromRaw(e,r=[]){return this.fromNode=new U(new x(e,r)),this}with(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("materialized",e,s.extractQueryNodes())),this}withNotMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withNotMaterialized","NOT_MATERIALIZED_CTE_NOT_SUPPORTED",new Error("NOT MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("not materialized",e,s.extractQueryNodes())),this}insert(e,r){let n=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,[this.interpreterUtils.stripComputedFromData(n)],r,o),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),l=Object.fromEntries(s.map((p,h)=>[p,a[h]]));this.insertNode=new re(this.fromNode,[l],r,o);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!o)return Array.isArray(m)&&m.length?m[0]:m})}insertMany(e,r){let n=e.map(s=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(s).map(a=>[a,s[a]])))),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,n,r,o),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return o?void 0:[];let s=await Promise.all(e.map(async c=>{let{columns:m,values:p}=this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert",this.dbType);return Object.fromEntries(m.map((h,f)=>[h,p[f]]))}));this.insertNode=new re(this.fromNode,s,r,o);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await J(a,l,u,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!o)return d})}upsert(e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(Object.keys(e)),s=Object.keys(r),a=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(e).map(l=>[l,e[l]])));return this.insertNode=new re(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),d=Object.fromEntries(l.map((f,T)=>[f,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,o,n,[e]);let{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),[d],void 0,true),new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning)]),p=await this.getSqlDataSource("write"),h=await J(c,m,p,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(h)?h:[h]})}upsertMany(e,r,n,o={updateOnConflict:true}){let s=this.interpreterUtils.filterComputedColumns(r),a=n.map(l=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(l).map(u=>[u,l[u]]))));return this.insertNode=new re(new U(this.model.table),a,void 0,true),this.onDuplicateNode=new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let l=[];if(await Promise.all(n.map(async p=>{let{columns:h,values:f}=this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert",this.dbType),T=Object.fromEntries(h.map((w,q)=>[w,f[q]]));l.push(T);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(l,e,s,o,n);let{sql:u,bindings:d}=this.astParser.parse([new re(new U(this.model.table),l,void 0,true),new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,n,o,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=K=>this.interpreterUtils.formatStringColumn("mssql",K),d=[],c=e.map(K=>`select ${a.map(v=>(d.push(K[v]),`@${d.length}`)).join(", ")}`),m=a.map(u).join(", "),p=c.join(" union all "),h=r.map(K=>`target.${u(K)} = source.${u(K)}`).join(" and "),f=n.filter(K=>!r.includes(K)).map(K=>`target.${u(K)} = source.${u(K)}`).join(", "),T=a.map(u).join(", "),w=a.map(K=>`source.${u(K)}`).join(", "),q=o.returning&&o.returning.length?o.returning.map(K=>`inserted.${u(K)}`).join(", "):a.map(K=>`inserted.${u(K)}`).join(", "),R=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",$=`merge into ${l} as target using (${p}) as source (${m}) on ${h} ${R} when not matched then insert (${T}) values (${w}) output ${q};`,A=await this.getSqlDataSource("write"),O=await J($,d,A,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(O)?O:[O]}update(e,r){let n=this.interpreterUtils.stripComputedFromData(e),o=Object.keys(n),s=Object.values(n);this.updateNode=new Ee(this.fromNode,o,s),this.returningNode=this.buildReturningNode("update",r);let a=this.returningNode!==null;return new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(o,s,"update",this.dbType);this.updateNode=new Ee(this.fromNode,l,u);let{sql:d,bindings:c}=this.astParser.parse(this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes])),m=await this.getSqlDataSource("write");return J(d,c,m,this.dbType,a?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:a?"fetch":"affectedRows"}})})}buildReturningNode(e,r){return !r?.length||!this.interpreterUtils.dialectEmitsReturning(this.dbType)?null:new xt(r,e==="delete"?"deleted":"inserted")}withReturningNode(e){if(!this.returningNode)return e;if(this.dbType==="mssql"){let[r,...n]=e;return [r,this.returningNode,...n]}return [...e,this.returningNode]}truncate(){return this.truncateNode=new qt(this.fromNode),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),n=await this.getSqlDataSource("write");await J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout});})}delete(e){this.deleteNode=new Mt(this.fromNode),this.returningNode=this.buildReturningNode("delete",e);let r=this.returningNode!==null;return new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:n,bindings:o}=this.astParser.parse(this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes])),s=await this.getSqlDataSource("write");return J(n,o,s,this.dbType,r?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:n=bt()}=e||{};return this.updateNode=new Ee(this.fromNode,[r],[n]),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:o,values:s}=this.interpreterUtils.prepareColumns([r],[n],"update",this.dbType);this.updateNode=new Ee(this.fromNode,o,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return J(a,l,u,this.dbType,"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return it(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),n=lt(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${n}`:n,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new H("*")]);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=W(this.modelSelectedColumns),e.distinctNode=W(this.distinctNode),e.distinctOnNode=W(this.distinctOnNode),e.selectNodes=W(this.selectNodes),e.withQuery=W(this.withQuery),e.joinNodes=W(this.joinNodes),e.whereNodes=W(this.whereNodes),e.groupByNodes=W(this.groupByNodes),e.havingNodes=W(this.havingNodes),e.orderByNodes=W(this.orderByNodes),e.lockQueryNodes=W(this.lockQueryNodes),e.unionNodes=W(this.unionNodes),e.withNodes=W(this.withNodes),e.comments=[...this.comments],e.hints=[...this.hints],e.schemaName=this.schemaName,e.fromNode=W(this.fromNode),e.limitNode=W(this.limitNode),e.offsetNode=W(this.offsetNode),e.returningNode=W(this.returningNode),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(){if(this.selectNodes.length||(this.selectNodes=[new H("*")]),this.schemaName){this.fromNode&&typeof this.fromNode.table=="string"&&(this.fromNode.schema=this.schemaName);for(let n of this.joinNodes)n.schema=this.schemaName;}if(this.insertNode)return [this.insertNode,this.onDuplicateNode].filter(Boolean);if(this.updateNode)return this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.deleteNode)return this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.truncateNode)return [this.truncateNode];let e=this.comments.map(n=>new Lt(n)),r=this.hints.length?[new Lt(this.hints.join(" "),true)]:[];return [...this.withNodes,...e,this.distinctNode,this.distinctOnNode,...this.selectNodes,...r,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}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let n=await e(),o=await r();return [n,o]}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 n=await this.getSqlDataSource(e);if(!(n!==this.sqlDataSource))return r(n);try{return await r(n)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:n.host,port:n.port,username:n.username,password:n.password,database:n.database,type:n.getDbType()}),await r(this.sqlDataSource);throw a}}};function Yf(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:mg(i)}function mg(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 Hl=ie(),ot=class i extends B{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Ut(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[n,o]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(n,o.columnName);}expandModelSelectColumns(){let e=this.selectNodes;if(!e.length){if(this.joinNodes.length)return;for(let[,r]of this.modelColumnsMap)r.expression||e.push(new H(r.databaseName,r.columnName));return}for(let r of e){if(r.isRawValue||r.alias!==void 0||typeof r.column!="string"||r.column.includes(".")||r.column==="*")continue;let n=this.modelColumnsMap.get(r.column);!n||n.expression||(r.alias=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(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(e){let r=await this.one();if(!r)throw new S(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(){await this.model.beforeFetch?.(this);let e=this.collectUserOutputNames();this.expandModelSelectColumns();let n=await super.many();if(!n.length)return [];let o=he(n,this.model,this.modelSelectedColumns,e);if(!o)return [];let s=Array.isArray(o)?o:[o];return 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){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;yield n,r+=n.length;}}async stream(e={}){await this.model.beforeFetch?.(this);let r=this.collectUserOutputNames();this.expandModelSelectColumns();let{sql:n,bindings:o}=this.unWrap(),s=await this.getSqlDataSource("read");return await on(n,o,s,e,{onData:async(l,u)=>{let d=he([u],this.model,this.modelSelectedColumns,r);d&&(this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),l.write(d));}})}async paginateWithCursor(e,r){return super.paginateWithCursor(e,r)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{returning:r.returning})}upsert(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return o.upsertMany(s,a,[l],{updateOnConflict:n.updateOnConflict??true,returning:n.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=r.length>0?Object.keys(r[0]):[];return o.upsertMany(e,s,r,{updateOnConflict:n.updateOnConflict??true,returning:n.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource.getTransactionBoundSqlDataSource()??this.sqlDataSource;return new st(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,n){return this.getModelManager(n?.trx).updateRecord(e,r,n)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let n=this.model.primaryKey;if(!n)throw new S(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let o=e[n],s=o?{[n]:o}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,n){let{column:o=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[o]:s};return this.getModelManager(n?.trx).updateRecord(e,a,{returning:n?.returning})}async firstOrInsert(e,r,n){let o=this.getModelManager(n?.trx),s=await o.findOne({where:e});if(s)return s;let a={...e,...r};return o.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,n,o,s={}){if(Array.isArray(n)||(n=[n]),!n.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new S(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=z(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=z(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=n.map((p,h)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...o?o(p,h):{}}));class c extends Ae{static get table(){return a.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await new st(c,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let n=r.returning,o=super.update(e,n);return new Y(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>{if(!n||!this.returningNode)return o;let s=await o;return he(s,this.model,n)})}softDelete(e={}){let r=super.softDelete(e);return new Y(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>r)}delete(e={}){let r=e.returning,n=super.delete(r);return new Y(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>{if(!r||!this.returningNode)return n;let o=await n;return he(o,this.model,r)})}async getCount(e="*"){this.buildCountQuery(e);let r=await this.one();return r?+r.total:0}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?+r.total:0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?+r.total:0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?+r.total:0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?+r.total:0}async paginate(e,r){let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof B)&&typeof e[1]=="string"){let[r,n]=e;return super.select(r,n),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}countDistinct(e,r){return super.countDistinct(e,r),this}sumDistinct(e,r){return super.sumDistinct(e,r),this}avgDistinct(e,r){return super.avgDistinct(e,r),this}rank(e,r){return super.rank(e,r),this}denseRank(e,r){return super.denseRank(e,r),this}rowNumber(e,r){return super.rowNumber(e,r),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,n){let o,s={strategy:"auto"};typeof r=="function"?(o=r,n&&(s=n)):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,o?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,n){return this.andHavingRelated(e,r,n)}andHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.whereExists(d),this}orHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.orWhereExists(d),this}notHavingRelated(e,r,n){return this.andNotHavingRelated(e,r,n)}andNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.whereNotExists(d),this}orNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=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,o),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=W(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let n=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,n);}));}async processRelationsWithStrategy(e){let r=e.length,n=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),o=async s=>{let a=Yf({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 n)await o(s);return}await Promise.all(n.map(o));}async loadRelationViaJoin(e,r){let n=e.relation,o=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,n,o).many();this.mapJoinedResultsToModels(a,r,n,o);}buildJoinQuery(e,r,n){let o=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)o.selectNodes.push(W(s));else for(let[s,a]of this.model.getColumnsByDatabaseName())a.expression||o.selectNodes.push(new H(`${this.model.table}.${s}`,void 0,void 0,true));for(let s of this.whereNodes){let a=W(s);this.qualifyWhereNodeColumns(a,this.model.table),o.whereNodes.push(a);}for(let s of this.groupByNodes)o.groupByNodes.push(W(s));for(let s of this.orderByNodes)o.orderByNodes.push(W(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(o.limitNode=W(this.limitNode)),this.offsetNode&&(o.offsetNode=W(this.offsetNode))),r.type){case "hasOne":case "hasMany":o.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":o.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;o.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),o.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(o,r,e,n);for(let s of e.whereNodes)o.whereNodes.push(W(s));for(let s of e.orderByNodes)o.orderByNodes.push(W(s));return o}selectRelationColumnsWithAlias(e,r,n,o){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=n.selectNodes.filter(m=>typeof m.column=="string"),c=d.some(m=>m.column==="*"||m.column.endsWith(".*"));if(d.length===0||c)for(let[m,p]of u)e.selectRaw(`${a.table}.${m} as ${s}${o}${p.columnName}`);else for(let m of d){let p=m.column,h=p.includes(".")?p.split(".").pop():p,f=u.get(h)||l.get(h),T=f?.databaseName??h,w=m.alias??f?.columnName??h;e.selectRaw(`${a.table}.${T} as ${s}${o}${w}`);}}mapJoinedResultsToModels(e,r,n,o){let{columnName:s,type:a}=n,l=n.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];u.has(c)||u.set(c,[]);let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.get(c).push(m));}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||[];});}else {let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];if(!u.has(c)){let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.set(c,m));}}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||null;});}}extractRelationDataFromRow(e,r,n){let o=`${r}${n}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(o)){let d=u.substring(o.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 M)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Re)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof $e)for(let n of e.nodes)this.qualifyWhereNodeColumns(n,r);}serializeRelationData(e,r){for(let n of Object.keys(e)){let o=r.get(n);o?.serialize&&e[n]!==null&&e[n]!==void 0&&(e[n]=o.serialize(e[n]));}}async loadRelationViaBatch(e,r){let n=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,n);}mapRelatedModelsToModels(e,r,n){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let o=new Map;n.forEach(m=>{let p=m[e.foreignKey];p&&o.set(String(p),m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=null;return}let h=o.get(String(p));m[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;n.forEach(m=>{if(!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=m[e.model.primaryKey];p&&s.set(String(p),m);}),r.forEach(m=>{let p=m[e.foreignKey];if(!p){m[e.columnName]=null;return}let h=s.get(String(p));m[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;n.forEach(m=>{let p=m[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=a.get(String(p))||[];m[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,c=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||z(d,this.model.modelCaseConvention);n.forEach(m=>{let p=m[c];if(p==null)return;let h=String(p);u.has(h)||u.set(h,[]),delete m[c],u.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=u.get(String(p))||[];m[e.columnName]=h;});break;default:throw new S(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,n){return this.getRelatedModelsQueryForRelation(e,r,n).many()}getRelatedModelsQueryForRelation(e,r,n){let o=this.getFilterValuesFromModelsForRelation(r,n);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,o);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,o);let l=Qe(Hl.crypto.randomBytes(6)),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(O=>O.isRawValue?O.column:`${this.interpreterUtils.formatStringColumn(this.dbType,O.column)} ${O.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let c=e.with(u,O=>O.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,o));s&&c.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&c.whereRaw(`rn_${l} > ${a}`);let m=e.modelSelectedColumns.map(O=>fo(O,u,e.model.table));return c.select(...m).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!n.length)return e;let h=e.limitNode?.limit,f=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(O=>O.includes(".")?O:`${r.model.table}.${O}`):[`${r.model.table}.*`];if(!h&&!f)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o);let w=Qe(Hl.crypto.randomBytes(6)),q=`${r.model.table}_cte_${w}`,D=e.orderByNodes.map(O=>{if(O.isRawValue)return O.column;let K=O.column.includes(".")?O.column:`${r.model.table}.${O.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,K)} ${O.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Qe(Hl.crypto.randomBytes(6))}_left_foreign_key`,$=e.with(q,O=>O.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,R]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${D}) as rn_${w}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o));h&&$.whereRaw(`rn_${w} <= ${h+(f||0)}`),f&&$.whereRaw(`rn_${w} > ${f}`);let A=T.map(O=>fo(O,q,e.model.table));return $.select(...A).select([`${q}.${R}`,p.leftForeignKey]).table(q);default:throw new S(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);case "belongsTo":return r.map(n=>n[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);default:throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,n,o){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 S(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}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new S(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}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===u.throughModel&&p.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let c=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${c} = ${m}`),n&&typeof o=="number"&&e.groupByRaw(c).andHavingRaw(`count(*) ${n} ${o}`);return}default:throw new S(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}};function Zf(){return {}}var st=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Zf(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,n])=>{e.orderBy(r,n);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many()}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,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,offset:t.offset});if(e===null)throw t.customError?t.customError:new S(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new S(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one()}insert(t,e={}){let r=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(t).map(u=>[u,t[u]]))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),[r],e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new Y(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(q){throw q}let{columns:u,values:d}=this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert",this.sqlType),c={};u.forEach((q,D)=>{let R=d[D];c[q]=R,t[q]??(t[q]=R);});let m=!e.returning||e.returning.length===0,{sql:p,bindings:h}=this.astParser.parse([new re(new U(this.model.table),[c],e.returning,m)]),f=await J(p,h,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(m)return;if(this.sqlType==="mysql")return this.handleMysqlInsert(f,[t],"one",e.returning);let T=f[0];return T?he([T],this.model,e.returning):t})}insertMany(t,e={}){let r=t.map(u=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(u).map(d=>[d,u[d]])))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),r,e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new Y(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}let u=t.map(T=>{let{columns:w,values:q}=this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert",this.sqlType),D={};return w.forEach((R,$)=>{let A=q[$];D[R]=A,T[R]??(T[R]=A);}),D}),d=!e.returning||e.returning.length===0,{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),u,e.returning,d)]),p=await J(c,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let h=p;return h.length?he(h,this.model,e.returning)||[]:[]})}upsertMany(t,e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(e),s=r.map(p=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(p).map(h=>[h,p[h]])))),a=new re(new U(this.model.table),s,void 0,true),l=n.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0;new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",l);let d=()=>{let p=this.astParser.parse([a]);return {sql:p.sql,bindings:p.bindings}},c=()=>{let p=this.astParser.parse([a]);return {sql:lt(this.sqlDataSource,p.sql),bindings:p.bindings}},m=()=>{let{sql:p,bindings:h}=c();return it(p,h)};return new Y(d,c,m,async()=>{let p=r.map(A=>{let{columns:O,values:K}=this.interpreterUtils.prepareColumns(Object.keys(A),Object.values(A),"insert",this.sqlType);return Object.fromEntries(O.map((le,v)=>[le,K[v]]))});if(this.sqlType==="mssql")return this.executeMssqlMerge(p,t,o,n,r);let h=!n.returning||n.returning.length===0,f=!h&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0,{sql:T,bindings:w}=this.astParser.parse([new re(new U(this.model.table),p,void 0,true),new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",f)]),q=await J(T,w,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(h)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(q.length<r.length&&!(n.updateOnConflict??true)){let K=t[0],le=r.map(ne=>ne[K]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(K,le).many()}return he(q,this.model,n.returning)||[]}let D=t[0],R=r.map(A=>A[D]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(D,R).many()})}async executeMssqlMerge(t,e,r,n,o){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=A=>this.interpreterUtils.formatStringColumn("mssql",A),u=[],d=t.map(A=>`select ${s.map(K=>(u.push(A[K]),`@${u.length}`)).join(", ")}`),c=s.map(l).join(", "),m=d.join(" union all "),p=e.map(A=>`target.${l(A)} = source.${l(A)}`).join(" and "),h=r.filter(A=>!e.includes(A)).map(A=>`target.${l(A)} = source.${l(A)}`).join(", "),f=s.map(l).join(", "),T=s.map(A=>`source.${l(A)}`).join(", "),w=n.returning&&n.returning.length?n.returning.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "):s.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "),D=(n.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",R=`merge into ${a} as target using (${m}) as source (${c}) on ${p} ${D} when not matched then insert (${f}) values (${T}) output ${w};`,$=await J(R,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});if($.length===0&&!(n.updateOnConflict??true)){let A=e[0],O=o.map(le=>le[A]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(A,O).many()}return $}async updateRecord(t,e,r){let n=new Set(this.model.getColumns().map(w=>w.columnName)),o=Object.keys(e).filter(w=>n.has(w)),s=o.map(w=>e[w]),{columns:a,values:l}=this.interpreterUtils.prepareColumns(o,s,"update",this.sqlType),{primaryKey:u}=this.model;if(!u)throw new S(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 c=r?.returning??[],m=c.length>0&&!this.interpreterUtils.hasComputedColumn(c)&&this.interpreterUtils.shouldFetchNatively(this.sqlType,"update"),{sql:p,bindings:h}=this.astParser.parse([new Ee(new U(this.model.table),a,l),new M(u,"and",false,"=",t),...m?[new xt(c)]:[]]),f=await J(p,h,this.sqlDataSource,this.sqlType,m?"rows":"affectedRows",m?{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}:void 0);if(!c.length)return;if(m){if(!f.length)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return he([f[0]],this.model,c)}let T=await this.findOneByPrimaryKey(t,r?.returning);if(!T)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return T}async deleteRecord(t){if(!this.model.primaryKey)throw new S(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new M(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:n}=this.astParser.parse([new Mt(new U(this.model.table)),e]);await J(r,n,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new ot(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,n){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?he([a],this.model):null}return he(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(...n??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let o=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...n||["*"]).whereIn(this.model.primaryKey,o).many();return r==="one"?s.length?s[0]:null:s}handleWhereCondition(t,e,r=false){if(e)for(let[n,o]of Object.entries(e))n==="$and"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{for(let l of o)this.handleWhereCondition(a,l,false);}):n==="$or"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of o)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,n,o,r);}applyFieldCondition(t,e,r,n=false){if(r==null||typeof r!="object"){r===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",r):t.where(e,"=",r);return}let o=r,s=o.op,a=o.value;switch(s){case "$eq":a===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?n?t.orWhereNotNull(e):t.whereNotNull(e):n?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":n?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":n?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":n?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":n?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;n?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;n?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":n?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":n?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":n?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":n?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":n?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":n?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":n?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":n?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":n?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":n?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:n?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var zl=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??bt()});Dt();var be=class{constructor(t){this.options=t;}static async createDriver(t){throw new S("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};ue();var Ht=class Ht extends be{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new Ht(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new L("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new L("mongodb");return new Ht(this.mongoClient)}};Ht.mongoClient=null;var gn=Ht;ue();var zt=class zt extends be{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new zt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new L("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new L("mssql");return new zt(this.mssqlClient)}};zt.mssqlClient=null;var bn=zt;ue();var Gt=class Gt extends be{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Gt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new L("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new L("mysql2");return new Gt(this.mysqlClient)}};Gt.mysqlClient=null;var Tn=Gt;ue();var Yt=class Yt extends be{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Yt(this.pgClient);let e=await import('pg').catch(()=>{throw new L("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new L("pg");return new Yt(this.pgClient)}};Yt.pgClient=null;var wn=Yt;ue();var Zt=class Zt extends be{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Zt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new L("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new L("sqlite3");return new Zt(this.sqlite3Client)}};Zt.sqlite3Client=null;var Sn=Zt;var me=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Tn.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await wn.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Sn.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await gn.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await bn.createDriver(),this.mssqlDriver;default:throw new S(`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;default:return null}}};me.mysqlDriver=null,me.pgDriver=null,me.sqliteDriver=null,me.mssqlDriver=null,me.mongodbDriver=null;Dt();ue();var Nn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.coerceNumericTypes&&!e.driverOptions?.types?{getTypeParser:(o,s)=>{let a=!s||s==="text";return a&&o===20?l=>BigInt(l):a&&o===1700?l=>Number.parseFloat(l):r.types.getTypeParser(o,s)}}:void 0;this.pool=new r.Pool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions,...n?{types:n}:{}});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.connect()}releaseConnection(t){t?.release();}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION"),e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`);}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=0,o=t.replace(/\?/g,()=>`$${++n}`);if(!r.signal)return (r.connection??this.pool).query(o,e);let s=r.connection??await this.pool.connect(),a=!r.connection,l=()=>{let u=s.processID;u!=null&&this.pool.query("SELECT pg_cancel_backend($1)",[u]).catch(()=>{});};r.signal.addEventListener("abort",l,{once:true});try{return await s.query(o,e)}finally{r.signal.removeEventListener("abort",l),a&&s.release();}}extract(t,e){return e==="rows"?t.rows:e==="raw"?t:t.rowCount}async stream(t,e,r,n){let o=r.connection,s=!o,a=o??await this.pool.connect(),l=await import('pg-query-stream').catch(()=>{throw new L("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,c=t.replace(/\?/g,()=>`$${++d}`),m=new l.default(c,e,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(m),h=0,f=false,T=false,w=q=>{if(s)try{a.release(q);}catch{}};return p.on("data",q=>{if(n.onData){h++,Promise.resolve(n.onData(u,q)).then(()=>{h--,f&&h===0&&!T&&(w(),u.end());}).catch(D=>{T=true,w(D),u.destroy(D);});return}u.write(q);}),p.on("end",()=>{f=true,h===0&&!T&&(w(),u.end());}),p.on("error",q=>{T=true,w(q),u.destroy(q);}),u}};var qn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=r.createPool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.getConnection()}releaseConnection(t){t?.release();}async beginTransaction(t,e){e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`),await t.beginTransaction();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){if(!r.signal)return (r.connection??this.pool).query(t,e);let n=r.connection??await this.pool.getConnection(),o=!r.connection,s=()=>{let a=n.threadId;a!=null&&this.pool.query(`KILL QUERY ${Number(a)}`).catch(()=>{});};r.signal.addEventListener("abort",s,{once:true});try{return await n.query(t,e)}finally{r.signal.removeEventListener("abort",s),o&&n.release();}}extract(t,e){let r=t;return e==="affectedRows"?r[0]?.affectedRows??0:e==="raw"?t:r[0]}async stream(t,e,r,n){let o=this.pool,s=r.connection??await o.getConnection(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=s.connection.query(t,e).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),d=0,c=false,m=false,p=()=>{try{s.release();}catch{}};return u.on("data",h=>{if(n.onData){d++,Promise.resolve(n.onData(a,h)).then(()=>{d--,c&&d===0&&!m&&(p(),a.end());}).catch(f=>{m=true,p(),a.destroy(f);});return}a.write(h);}),u.on("end",()=>{c=true,d===0&&!m&&(p(),a.end());}),u.on("error",h=>{m=true,p(),a.destroy(h);}),a.on("close",()=>{p();}),a}};var Cn=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=new r.Database(String(e.database??":memory:"),e.driverOptions?.mode??void 0,n=>{if(n)throw new S("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});}createPool(){}async closePool(){await new Promise((t,e)=>{this.pool.close(r=>{r&&e(r),t();});});}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){return await this.promisify(t,e,r)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.pool;return new Gl(o,t,e,{onData:n.onData})}promisify(t,e,r){let n=r.sqlLiteOptions??{},o=n.mode||"fetch",s=n.customConnection??r.connection??this.pool;if(["begin","begin transaction","commit","rollback"].includes(t.trim().toLowerCase()))return new Promise((u,d)=>{s.run(t,e,function(c){c&&d(c),u(this.changes);});});if(o==="fetch")return new Promise((u,d)=>{s.all(t,e,(c,m)=>{c&&d(c),u(m||[]);});});if(!n?.typeofModel)return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});});if(o==="insertOne"||o==="insertMany"){let u=`${t} returning *`;return new Promise((d,c)=>{s.all(u,e,(m,p)=>{if(m)return c(m);d(p||[]);});})}return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});})}},Gl=class extends Readable{constructor(t,e,r=[],n){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=n;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(n,o)=>{if(n){r=true,this.emit("error",n);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,o)).then(()=>{if(!r){if(s){this.push(a);return}this.push(o);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},n=>{if(n){r=true,this.emit("error",n);return}e=true,t===0&&!r&&this.push(null);});}};ue();var Rn=class{constructor(t,e,r){this.dialect="mssql";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.driverOptions,{options:o,...s}=n??{};this.pool=new r.ConnectionPool({server:e.host??"localhost",port:e.port,database:e.database,user:e.username,password:e.password,...s,options:{trustServerCertificate:E.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...o,abortTransactionOnError:false,enableImplicitTransactions:false}});}async createPool(){await this.pool.connect();}async closePool(){await this.pool.close();}async reserveConnection(){return this.pool.transaction()}releaseConnection(){}async beginTransaction(t,e){if(e.isolationLevel){let r=await this.getMssqlTransactionLevel(e.isolationLevel);await t.begin(r);return}await t.begin();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){let n=this.pool,o=r.connection?r.connection.request():n.request();e.forEach((l,u)=>{o.input(`p${u}`,l);});let s=0,a=t.replace(/\?|@(\d+)/g,()=>`@p${s++}`);if(r.signal){let l=()=>{try{o.cancel();}catch{}};r.signal.addEventListener("abort",l,{once:true});try{return await o.query(a)}finally{r.signal.removeEventListener("abort",l);}}return o.query(a)}extract(t,e){return e==="affectedRows"?t.rowsAffected[0]:e==="raw"?t:t.recordset}async stream(t,e,r,n){let o=r.connection??this.pool,s=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),a=o.request();a.stream=true,e.forEach((p,h)=>{a.input(`p${h}`,p);});let l=0,u=t.replace(/\?|@(\d+)/g,()=>`@p${l++}`),d=0,c=false,m=false;return a.on("row",p=>{if(!m){if(n.onData){d++,Promise.resolve(n.onData(s,p)).then(()=>{d--,c&&d===0&&!m&&s.end();}).catch(h=>{m=true,s.destroy(h);});return}s.write(p);}}),a.on("error",p=>{m=true,s.destroy(p);}),a.on("done",()=>{c=true,d===0&&!m&&s.end();}),a.query(u),s}async getMssqlTransactionLevel(t){let e=await import('mssql').then(r=>r.default.ISOLATION_LEVEL).catch(r=>{throw g.error(r),new L("mssql")});switch(t){case "READ UNCOMMITTED":return e.READ_UNCOMMITTED;case "READ COMMITTED":return e.READ_COMMITTED;case "REPEATABLE READ":return e.REPEATABLE_READ;case "SERIALIZABLE":return e.SERIALIZABLE;default:throw new S("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${t}`)}}};var bg=()=>{ge({name:"pg",dialects:["postgres","cockroachdb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Nn(i,t,e)}}),ge({name:"mysql2",dialects:["mysql","mariadb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new qn(i,t,e)}}),ge({name:"sqlite3",dialects:["sqlite"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Cn(i,t,e)}}),ge({name:"mssql",dialects:["mssql"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Rn(i,t,e)}});};bg();var Cg=async i=>{if(i==="bun"){await(await Promise.resolve().then(()=>(ay(),iy))).registerBunDrivers();return}if(i==="web"){(await Promise.resolve().then(()=>(tu(),eu))).registerWebDrivers();return}if(i==="react-native"){await(await Promise.resolve().then(()=>(tu(),eu))).registerReactNativeDrivers();return}},Dn=async(i,t)=>{let e=ur(t?.jsEnvironment);await Cg(e);let r=await ey(i,e,t?.driver,t);return await r.createPool(),r};var er=class er{constructor(){}static run(t,e){return er.storage.run(t,e)}static getTransaction(){return er.storage.getStore()}};er.storage=new AsyncLocalStorage;var He=er;var tr=class i{constructor(t,e,r=false,n=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Qe(ie().crypto.randomBytes(16)),this.isolationLevel=e,this.isNested=r,this.nestingDepth=n;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await He.run(e,()=>t(e));return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){if(this.getIsolationLevelQuery(),this.isNested){let r=this.getSavePointName();this.sql.type==="mssql"?await this.sql.rawQuery(`SAVE TRANSACTION ${r}`):await this.sql.rawQuery(`SAVEPOINT ${r}`),this.isActive=true;return}(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("BEGIN TRANSACTION",this.sql.logs);let t=this.sql.driverAdapter,e=this.sql.sqlConnection;if(!t||!e)throw new S("TRANSACTION::transaction","CONNECTION_NOT_ESTABLISHED");await t.beginTransaction(e,{isolationLevel:this.isolationLevel,rawQuery:(r,n)=>this.sql.rawQuery(r,n??[])}),this.isActive=true;}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("COMMIT",this.sql.logs),e&&r&&await e.commitTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new S("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("ROLLBACK",this.sql.logs),e&&r&&await e.rollbackTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async releaseConnection(){if(this.connectionReleased)return;let t=null;try{this.sql.driverAdapter?.releaseConnection(this.sql.sqlConnection);}catch(e){t=e,g.error(e);}this.sql.sqlConnection=null;try{await this.sql.disconnect();}catch(e){g.warn(`Transaction::releaseConnection - disconnect failed: ${e?.message??e}`);}if(this.connectionReleased=true,t)throw t}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new S("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new S("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}};var ru=Symbol.for("hysteria.orm.SqlDataSource"),my,py,Be=class i extends(py=kt,my=ru,py){constructor(e){super(e);this[my]=true;this.globalTransaction=null;this.globalTransactionLock=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.lockConnection=null;this.lockKeyToId=new Map;this.driverAdapter=null;this.id=ie().crypto.randomUUID();this.logicalSourceId=ie().crypto.randomUUID();this.cacheAdapter=new hr;this.migrationConfig={path:E.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.zodEngine=null;this.lazyLoad=false;this.connecting=null;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:vt(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(n=>new i(n)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure,this.lazyLoad=e?.lazyLoad??false,this.clsEnabled=e?.clsEnabled??true;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&ru in e&&e[ru]===true}get isClsEnabled(){return this.clsEnabled}getOnSlaveServerFailure(){return this.onSlaveServerFailure}addObserver(e){return this.observerChain||(this.observerChain=new Ft([])),this.observerChain.add(e),this}static async useConnection(e,r){let n=new i(e);await n.connect();try{await r(n),n.isConnected&&await n.disconnect();}catch(o){throw n.isConnected&&await n.disconnect(),o}}async connect(){if(this.isConnected)throw new S("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");try{this.driverAdapter=await Dn(this.sqlType,this.inputDetails),this.sqlPool=this.driverAdapter.pool??null,this.ownsPool=!0,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.driverAdapter=await Dn(e.sqlType,e.inputDetails),e.sqlPool=e.driverAdapter.pool??null,e.ownsPool=!0;}));}catch(e){this.sqlPool=null,this.ownsPool=false;for(let r of this.slaves)r.ownsPool&&(r.sqlPool=null,r.ownsPool=false);throw e}}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new S("SqlDataSource::ensureConnected","CONNECTION_NOT_ESTABLISHED");this.connecting||(this.connecting=this.connect().finally(()=>{this.connecting=null;})),await this.connecting;}}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){let e=this;return new Proxy(this._models,{get(r,n){if(typeof n=="string"&&n in r)return e.from(r[n])}})}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}getTransactionBoundSqlDataSource(){if(this.globalTransaction?.isActive)return this.globalTransaction.sql;if(this.clsEnabled){let e=He.getTransaction();if(e?.isActive&&e.sql.logicalSourceId===this.logicalSourceId)return e.sql}return null}async useCache(e,r,...n){if(!this.cacheAdapter)throw new S("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new S("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=o.length,a=typeof r=="number"&&s===n.length,l,u=[];a?(l=r,u=n):(l=void 0,u=r!==void 0?[r,...n]:n);let d=Hn(JSON.stringify(u)),c=d?`${e}:${d}`:e,m=await this.cacheAdapter.get(c);if(m!==void 0)return m;let p=await o(...u);return await this.cacheAdapter.set(c,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new S("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(n.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Hn(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.id=this.id,r.logicalSourceId=this.logicalSourceId,r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.driverAdapter=await Dn(r.sqlType,this.inputDetails),r.sqlPool=r.driverAdapter.pool,r.ownsPool=true):(r.driverAdapter=this.driverAdapter,r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let n=this.getTransactionBoundSqlDataSource()??this;if(typeof e=="string"){let o=new B(zl(e,r),n);return r?.alias&&o.table(e,r.alias),o}return new ot(e,n)}fromRaw(e,r=[],n){let o=this.getTransactionBoundSqlDataSource()??this;return new B(zl("",n),o).fromRaw(e,r)}schema(){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Wt(this,this.getDbType())}async startGlobalTransaction(e){for(;this.globalTransactionLock;)await this.globalTransactionLock;if(this.globalTransaction?.isActive)throw new S("SqlDataSource::startGlobalTransaction","GLOBAL_TRANSACTION_ALREADY_STARTED");let r=()=>{};this.globalTransactionLock=new Promise(n=>{r=n;});try{let n=await this.clone();return n.sqlConnection=await n.getConnection(),this.globalTransaction=new tr(n,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}finally{r(),this.globalTransactionLock=null;}}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new S("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");try{await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}try{await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async transaction(e,r){let n=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let o=this.clsEnabled?He.getTransaction():void 0;if(o?.isActive&&o.sql.logicalSourceId===this.logicalSourceId)return typeof e=="function"?o.nestedTransaction(e):o.nestedTransaction();let s=await this.clone();s.sqlConnection=await s.getConnection();let a=new tr(s,n?.isolationLevel);if(await a.transaction(),typeof e=="function")try{let l=this.clsEnabled?await He.run(a,()=>e(a)):await e(a);return await a.commit({throwErrorOnInactiveTransaction:!1}),l}catch(l){throw await a.rollback({throwErrorOnInactiveTransaction:false}),l}return a}getModelManager(e){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");let r=this.getTransactionBoundSqlDataSource()??this;return new st(e,r)}getPool(){if(!this.sqlPool)throw this.lazyLoad?new S("SqlDataSource::getPool - call ensureConnected() or connect() first when using lazyLoad","CONNECTION_NOT_ESTABLISHED"):new S("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;await this.ensureConnected();let e=this.driverAdapter;if(!e)throw new S("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");return e.reserveConnection()}async disconnect(){if(!this.isConnected){g.warn("Connection already closed or not established");return}if(!this.ownsPool){if(this.sqlConnection)try{this.driverAdapter?.releaseConnection(this.sqlConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing borrowed connection failed: ${e?.message??e}`);}this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}if(this.lockConnection){try{this.driverAdapter?.releaseConnection(this.lockConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing lock connection failed: ${e?.message??e}`);}this.lockConnection=null,this.lockKeyToId.clear();}await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),g.warn("Closing connection"),await this.driverAdapter?.closePool(),this.sqlPool=null,this.driverAdapter=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,jsEnvironment:this.inputDetails.jsEnvironment,driver:this.inputDetails.driver}}async introspectSchema(){let e=this.getDbType(),r;e==="postgres"||e==="cockroachdb"?r=`
260
260
  SELECT table_schema AS schema_name, table_name
261
261
  FROM information_schema.tables
262
262
  WHERE table_type = 'BASE TABLE'
@@ -355,10 +355,10 @@ export default class extends BaseSeeder {
355
355
  console.log('Seeder completed');
356
356
  }
357
357
  }
358
- `}};var Rg=(i,t,e)=>{let r=e||"database/seeders",n=t?".js":".ts",s=`${Date.now()}_${i}${n}`;ae.existsSync(r)||(ae.mkdirSync(r,{recursive:true}),g.info(`Created seeders directory: ${r}`));let a=yt.join(r,s),l=vn.seederTemplate();ae.writeFileSync(a,l),g.info(`Seeder created successfully: ${a}`);},fy=Rg;var _g=async(i,t,e)=>{let r=[];for(let n of t){let o=yt.resolve(process.cwd(),n);ae.existsSync(o)||(g.error(`Path not found: ${o}`),process.exit(1));let s=ae.statSync(o);if(s.isDirectory()){let a=ae.readdirSync(o).filter(l=>l.endsWith(".ts")||l.endsWith(".js")).sort();for(let l of a)r.push({file:l,folder:o});}else if(s.isFile()){let a=yt.basename(o),l=yt.dirname(o);a.endsWith(".ts")||a.endsWith(".js")?r.push({file:a,folder:l}):(g.error(`File must be a .ts or .js file: ${a}`),process.exit(1));}}if(!r.length){g.info("No seeders found");return}g.info(`Found ${r.length} seeder(s) to run`),i.isConnected||await i.connect();for(let{file:n,folder:o}of r)try{g.info(`Running seeder: ${n}`);let s=yt.resolve(o,n),a=await ft(s,e);if(!a.default){g.error(`Seeder ${n} does not export a default class`);continue}let l=new a.default(i);if(typeof l.run!="function"){g.error(`Seeder ${n} must have a run() method. Make sure it extends BaseSeeder from hysteria-orm`);continue}await l.run(),g.info(`\u2713 Completed seeder: ${n}`);}catch(s){throw g.error(`Failed to run seeder ${n}: ${s}`),s}g.info("All seeders completed successfully");},yy=_g;function Q(i){return {_phantom:void 0,_apply:i}}function hy(i){return Q((t,e)=>{_.date(i??{},false)(t,e);})}hy.string=function(t){return Q((e,r)=>{_.date(t??{},true)(e,r);})};function gy(i){return Q((t,e)=>{_.datetime(i??{},false)(t,e);})}gy.string=function(t){return Q((e,r)=>{_.datetime(t??{},true)(e,r);})};function by(i){return Q((t,e)=>{_.timestamp(i??{},false)(t,e);})}by.string=function(t){return Q((e,r)=>{_.timestamp(t??{},true)(e,r);})};function Ty(i){return Q((t,e)=>{_.time(i??{},false)(t,e);})}Ty.string=function(t){return Q((e,r)=>{_.time(t??{},true)(e,r);})};ue();var wy=Symbol("mongoProperties");function iu(){return (i,t)=>{let e=z.getMetadata(wy,i)||[];e.push(t),z.defineMetadata(wy,e,i);}}var or=class extends Ve{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}};pu([iu()],or.prototype,"id");ue();Dt();ue();function xg(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 Og=new Set(["table","primaryKey","softDeleteColumn","softDeleteValue","modelCaseConvention","databaseCaseConvention","getColumns","getColumnsByName","getColumnsByDatabaseName","getRelations","getIndexes","getUniques","getChecks","beforeFetch","afterFetch","beforeInsert","beforeInsertMany","beforeUpdate","beforeDelete","query","all","first","find","findOneOrFail","findOne","findBy","findOneBy","findOneByPrimaryKey","refresh","sync","insert","insertMany","updateRecord","firstOrInsert","upsert","upsertMany","deleteRecord","save","softDelete","truncate","sqlInstance","getTableInfo","getIndexInfo","getTableSchema","prototype","constructor"]);function Ny(i,t){let e=xg(i);switch(t){case "pascal":return Xn(e);case "camel":return br(e);case "snake":return gr(e);default:return e}}function qy(i){return Og.has(i)?{name:`${i}_`,wasSanitized:true}:{name:i,wasSanitized:false}}function Cy(i,t){switch(t){case "snake":return `${gr(i)}.ts`;case "camel":return `${i}.ts`;default:return `${i}.ts`}}function Ry(i,t){let{dataType:e,isNullable:r,defaultValue:n,length:o,precision:s,scale:a,withTimezone:l,unsigned:u}=t,d={};if(r||(d.nullable=false),n!=null){let p=String(n);!p.includes("(")&&!p.includes("CURRENT_")&&(d.default=n);}o!=null&&(d.length=o),s!=null&&(d.precision=s),a!=null&&(d.scale=a),u&&(d.unsigned=true);let c=e.toLowerCase();c.includes("timestamp")&&l&&(d.withTimezone=true);let m="string";return c.includes("varchar")||c.includes("char")?m="string":c.includes("text")?m="text":c==="integer"||c==="int"||c==="int4"?m="integer":c==="bigint"||c==="int8"?m="bigInteger":c==="smallint"||c==="int2"?m="smallint":c==="boolean"||c==="bool"?m="boolean":c.includes("timestamp")?m="timestamp":c==="date"?m="date":c==="time"?m="time":c==="uuid"?m="uuid":c==="json"?m="json":c==="jsonb"?m="jsonb":c==="decimal"||c==="numeric"?m="decimal":c==="float"||c==="real"||c==="double"||c==="double precision"?m="float":c==="binary"||c==="bytea"?m="binary":c==="enum"&&(m="enum",t.enumValues&&(d.enumValues=t.enumValues)),i==="mysql"&&c.includes("tinyint")&&o===1&&(m="boolean"),{method:m,options:d}}function ze(i){return JSON.stringify(i)}function _y(i){return i==null?"null":typeof i=="string"?ze(i):typeof i=="boolean"?i?"true":"false":typeof i=="number"?String(i):Array.isArray(i)?`[${i.map(_y).join(", ")}]`:String(i)}function My(i,t,e,r){let n=[],o=new Set(t.primaryKey?.columns||[]),s=new Map;for(let u of t.foreignKeys)for(let d=0;d<u.columns.length;d++){let c=u.columns[d],m=u.referencedColumns[d];s.has(c)||s.set(c,{referencedTable:u.referencedTable,referencedColumns:[m],onDelete:u.onDelete,onUpdate:u.onUpdate});}n.push('import { col, defineModel } from "hysteria-orm";'),n.push(""),n.push(`export const ${i} = defineModel(${ze(i)}, {`),n.push(" columns: {");for(let u of t.columns){let c=qy(u.name).name,m=o.has(u.name),{method:p,options:h}=Ry(e,u),f=[];for(let[D,R]of Object.entries(h))R!=null&&f.push(`${D}: ${_y(R)}`);let T=f.length>0?`{ ${f.join(", ")} }`:"",w=T?`col.${p}(${T})`:`col.${p}()`,q=s.get(u.name);if(q){let D=q.referencedColumns.join(", "),R=`/** @fk references ${q.referencedTable}(${D})`;q.onDelete&&(R+=` \u2014 onDelete: ${q.onDelete}`),q.onUpdate&&(R+=` \u2014 onUpdate: ${q.onUpdate}`),R+=" */",n.push(` ${R}`);}m&&(n.push(" // Primary key column"),(p==="integer"||p==="bigInteger")&&n.push(" // TODO: may be auto-increment, verify manually")),n.push(` ${c}: ${w},`);}n.push(" },");let a=t.indexes.filter(u=>!u.isUnique);if(a.length>0){n.push(" indexes: [");for(let u of a)u.name?n.push(` { columns: [${u.columns.map(ze).join(", ")}], name: ${ze(u.name)} },`):n.push(` [${u.columns.map(ze).join(", ")}],`);n.push(" ],");}let l=t.indexes.filter(u=>u.isUnique);if(l.length>0){n.push(" uniques: [");for(let u of l)u.name?n.push(` { columns: [${u.columns.map(ze).join(", ")}], name: ${ze(u.name)} },`):n.push(` [${u.columns.map(ze).join(", ")}],`);n.push(" ],");}return n.push("});"),n.push(""),n.push(`export type ${i}Type = InstanceType<typeof ${i}>;`),n.push(""),n.join(`
358
+ `}};var xg=(i,t,e)=>{let r=e||"database/seeders",n=t?".js":".ts",s=`${Date.now()}_${i}${n}`;ae.existsSync(r)||(ae.mkdirSync(r,{recursive:true}),g.info(`Created seeders directory: ${r}`));let a=yt.join(r,s),l=vn.seederTemplate();ae.writeFileSync(a,l),g.info(`Seeder created successfully: ${a}`);},fy=xg;var Og=async(i,t,e)=>{let r=[];for(let n of t){let o=yt.resolve(process.cwd(),n);ae.existsSync(o)||(g.error(`Path not found: ${o}`),process.exit(1));let s=ae.statSync(o);if(s.isDirectory()){let a=ae.readdirSync(o).filter(l=>l.endsWith(".ts")||l.endsWith(".js")).sort();for(let l of a)r.push({file:l,folder:o});}else if(s.isFile()){let a=yt.basename(o),l=yt.dirname(o);a.endsWith(".ts")||a.endsWith(".js")?r.push({file:a,folder:l}):(g.error(`File must be a .ts or .js file: ${a}`),process.exit(1));}}if(!r.length){g.info("No seeders found");return}g.info(`Found ${r.length} seeder(s) to run`),i.isConnected||await i.connect();for(let{file:n,folder:o}of r)try{g.info(`Running seeder: ${n}`);let s=yt.resolve(o,n),a=await ft(s,e);if(!a.default){g.error(`Seeder ${n} does not export a default class`);continue}let l=new a.default(i);if(typeof l.run!="function"){g.error(`Seeder ${n} must have a run() method. Make sure it extends BaseSeeder from hysteria-orm`);continue}await l.run(),g.info(`\u2713 Completed seeder: ${n}`);}catch(s){throw g.error(`Failed to run seeder ${n}: ${s}`),s}g.info("All seeders completed successfully");},yy=Og;function Q(i){return {_phantom:void 0,_apply:i}}function hy(i){return Q((t,e)=>{_.date(i??{},false)(t,e);})}hy.string=function(t){return Q((e,r)=>{_.date(t??{},true)(e,r);})};function gy(i){return Q((t,e)=>{_.datetime(i??{},false)(t,e);})}gy.string=function(t){return Q((e,r)=>{_.datetime(t??{},true)(e,r);})};function by(i){return Q((t,e)=>{_.timestamp(i??{},false)(t,e);})}by.string=function(t){return Q((e,r)=>{_.timestamp(t??{},true)(e,r);})};function Ty(i){return Q((t,e)=>{_.time(i??{},false)(t,e);})}Ty.string=function(t){return Q((e,r)=>{_.time(t??{},true)(e,r);})};ue();var wy=Symbol("mongoProperties");function iu(){return (i,t)=>{let e=G.getMetadata(wy,i)||[];e.push(t),G.defineMetadata(wy,e,i);}}var or=class extends Ve{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}};pu([iu()],or.prototype,"id");ue();Dt();ue();function Ag(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 $g=new Set(["table","primaryKey","softDeleteColumn","softDeleteValue","modelCaseConvention","databaseCaseConvention","getColumns","getColumnsByName","getColumnsByDatabaseName","getRelations","getIndexes","getUniques","getChecks","beforeFetch","afterFetch","beforeInsert","beforeInsertMany","beforeUpdate","beforeDelete","query","all","first","find","findOneOrFail","findOne","findBy","findOneBy","findOneByPrimaryKey","refresh","sync","insert","insertMany","updateRecord","firstOrInsert","upsert","upsertMany","deleteRecord","save","softDelete","truncate","sqlInstance","getTableInfo","getIndexInfo","getTableSchema","prototype","constructor"]);function Ny(i,t){let e=Ag(i);switch(t){case "pascal":return Xn(e);case "camel":return br(e);case "snake":return gr(e);default:return e}}function qy(i){return $g.has(i)?{name:`${i}_`,wasSanitized:true}:{name:i,wasSanitized:false}}function Cy(i,t){switch(t){case "snake":return `${gr(i)}.ts`;case "camel":return `${i}.ts`;default:return `${i}.ts`}}function Ry(i,t){let{dataType:e,isNullable:r,defaultValue:n,length:o,precision:s,scale:a,withTimezone:l,unsigned:u}=t,d={};if(r||(d.nullable=false),n!=null){let p=String(n);!p.includes("(")&&!p.includes("CURRENT_")&&(d.default=n);}o!=null&&(d.length=o),s!=null&&(d.precision=s),a!=null&&(d.scale=a),u&&(d.unsigned=true);let c=e.toLowerCase();c.includes("timestamp")&&l&&(d.withTimezone=true);let m="string";return c.includes("varchar")||c.includes("char")?m="string":c.includes("text")?m="text":c==="integer"||c==="int"||c==="int4"?m="integer":c==="bigint"||c==="int8"?m="bigInteger":c==="smallint"||c==="int2"?m="smallint":c==="boolean"||c==="bool"?m="boolean":c.includes("timestamp")?m="timestamp":c==="date"?m="date":c==="time"?m="time":c==="uuid"?m="uuid":c==="json"?m="json":c==="jsonb"?m="jsonb":c==="decimal"||c==="numeric"?m="decimal":c==="float"||c==="real"||c==="double"||c==="double precision"?m="float":c==="binary"||c==="bytea"?m="binary":c==="enum"&&(m="enum",t.enumValues&&(d.enumValues=t.enumValues)),i==="mysql"&&c.includes("tinyint")&&o===1&&(m="boolean"),{method:m,options:d}}function ze(i){return JSON.stringify(i)}function _y(i){return i==null?"null":typeof i=="string"?ze(i):typeof i=="boolean"?i?"true":"false":typeof i=="number"?String(i):Array.isArray(i)?`[${i.map(_y).join(", ")}]`:String(i)}function My(i,t,e,r){let n=[],o=new Set(t.primaryKey?.columns||[]),s=new Map;for(let u of t.foreignKeys)for(let d=0;d<u.columns.length;d++){let c=u.columns[d],m=u.referencedColumns[d];s.has(c)||s.set(c,{referencedTable:u.referencedTable,referencedColumns:[m],onDelete:u.onDelete,onUpdate:u.onUpdate});}n.push('import { col, defineModel } from "hysteria-orm";'),n.push(""),n.push(`export const ${i} = defineModel(${ze(i)}, {`),n.push(" columns: {");for(let u of t.columns){let c=qy(u.name).name,m=o.has(u.name),{method:p,options:h}=Ry(e,u),f=[];for(let[D,R]of Object.entries(h))R!=null&&f.push(`${D}: ${_y(R)}`);let T=f.length>0?`{ ${f.join(", ")} }`:"",w=T?`col.${p}(${T})`:`col.${p}()`,q=s.get(u.name);if(q){let D=q.referencedColumns.join(", "),R=`/** @fk references ${q.referencedTable}(${D})`;q.onDelete&&(R+=` \u2014 onDelete: ${q.onDelete}`),q.onUpdate&&(R+=` \u2014 onUpdate: ${q.onUpdate}`),R+=" */",n.push(` ${R}`);}m&&(n.push(" // Primary key column"),(p==="integer"||p==="bigInteger")&&n.push(" // TODO: may be auto-increment, verify manually")),n.push(` ${c}: ${w},`);}n.push(" },");let a=t.indexes.filter(u=>!u.isUnique);if(a.length>0){n.push(" indexes: [");for(let u of a)u.name?n.push(` { columns: [${u.columns.map(ze).join(", ")}], name: ${ze(u.name)} },`):n.push(` [${u.columns.map(ze).join(", ")}],`);n.push(" ],");}let l=t.indexes.filter(u=>u.isUnique);if(l.length>0){n.push(" uniques: [");for(let u of l)u.name?n.push(` { columns: [${u.columns.map(ze).join(", ")}], name: ${ze(u.name)} },`):n.push(` [${u.columns.map(ze).join(", ")}],`);n.push(" ],");}return n.push("});"),n.push(""),n.push(`export type ${i}Type = InstanceType<typeof ${i}>;`),n.push(""),n.join(`
359
359
  `)}function xy(i){let t=[];for(let e of i)t.push(`export * from "./${e}";`);return t.push(""),t.join(`
360
- `)}var Dg=["pg_","information_schema","mysql","sys","performance_schema","sqlite_"];function Ag(i){let t=i.toLowerCase();return Dg.some(e=>t.startsWith(e))}async function au(i,t){let{outDir:e,naming:r,dry:n}=t;g.info("Starting database introspection");let o=i.getDbType();g.info(`Database dialect: ${o}`);let s=await i.introspectSchema();if(!s||s.length===0){g.warn("No tables found in database");return}let a=[];for(let d of s)for(let c of d.tables)Ag(c.name)||a.push(c.name);if(a.length===0){g.warn("No user tables found in database (system tables excluded)");return}g.info(`Found ${a.length} tables to process`);let l=[],u=[];for(let d of a){g.info(`Processing table: ${d}`);try{let c=await i.getTableSchema(d);if(c.columns.length===0){g.warn(`Table ${d} has no columns, skipping`);continue}let m=Ny(d,r),p=Cy(m,r),h=My(d,c,o,{naming:r});l.push(m),n?(g.info(`[DRY RUN] Would generate: ${p}`),g.info("---"),g.info(h),g.info("---")):u.push({fileName:p,content:h});}catch(c){g.error(`Failed to process table ${d}: ${c}`);}}if(!n){ae.existsSync(e)||(ae.mkdirSync(e,{recursive:true}),g.info(`Created output directory: ${e}`));for(let{fileName:d,content:c}of u){let m=yt.join(e,d);ae.writeFileSync(m,c,"utf-8"),g.info(`Generated: ${m}`);}if(l.length>0){let d=xy(l),c=yt.join(e,"index.ts");ae.writeFileSync(c,d,"utf-8"),g.info(`Generated: ${c}`);}}g.info(`
361
- Summary:`),g.info(` Tables processed: ${l.length}`),n?g.info(" Mode: Dry run (no files written)"):(g.info(` Output directory: ${e}`),g.info(` Files generated: ${u.length+1}`));}var Dy={devDependencies:{"@types/ioredis":"^5.0.0","@types/mongodb":"^4.0.7","@types/mssql":"^9.1.11","@types/pg":"^8.20.0","@types/sqlite3":"^5.1.0",esbuild:"^0.28.0",ioredis:"^5.10.1",mongodb:"^7.1.1",mssql:"^12.2.1",mysql2:"^3.20.0",pg:"^8.20.0",sqlite3:"^6.0.1",typescript:"^6.0.2"}};var $y=()=>ae.existsSync(yt.join(process.cwd(),"yarn.lock"))?["yarn","add"]:ae.existsSync(yt.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add"]:ae.existsSync(yt.join(process.cwd(),"package-lock.json"))?["npm","install"]:ae.existsSync(yt.join(process.cwd(),"bun.lockb"))?["bun","add"]:ae.existsSync(yt.join(process.cwd(),"deno.lock"))?["deno","add"]:["npm","install"],Ay=async(i,t,e,r)=>{let n=Ig.createInterface({input:process.stdin,output:process.stdout}),o=e.join(", "),s=`Do you want to install the following dependencies using ${t}?
360
+ `)}var vg=["pg_","information_schema","mysql","sys","performance_schema","sqlite_"];function Ig(i){let t=i.toLowerCase();return vg.some(e=>t.startsWith(e))}async function au(i,t){let{outDir:e,naming:r,dry:n}=t;g.info("Starting database introspection");let o=i.getDbType();g.info(`Database dialect: ${o}`);let s=await i.introspectSchema();if(!s||s.length===0){g.warn("No tables found in database");return}let a=[];for(let d of s)for(let c of d.tables)Ig(c.name)||a.push(c.name);if(a.length===0){g.warn("No user tables found in database (system tables excluded)");return}g.info(`Found ${a.length} tables to process`);let l=[],u=[];for(let d of a){g.info(`Processing table: ${d}`);try{let c=await i.getTableSchema(d);if(c.columns.length===0){g.warn(`Table ${d} has no columns, skipping`);continue}let m=Ny(d,r),p=Cy(m,r),h=My(d,c,o,{naming:r});l.push(m),n?(g.info(`[DRY RUN] Would generate: ${p}`),g.info("---"),g.info(h),g.info("---")):u.push({fileName:p,content:h});}catch(c){g.error(`Failed to process table ${d}: ${c}`);}}if(!n){ae.existsSync(e)||(ae.mkdirSync(e,{recursive:true}),g.info(`Created output directory: ${e}`));for(let{fileName:d,content:c}of u){let m=yt.join(e,d);ae.writeFileSync(m,c,"utf-8"),g.info(`Generated: ${m}`);}if(l.length>0){let d=xy(l),c=yt.join(e,"index.ts");ae.writeFileSync(c,d,"utf-8"),g.info(`Generated: ${c}`);}}g.info(`
361
+ Summary:`),g.info(` Tables processed: ${l.length}`),n?g.info(" Mode: Dry run (no files written)"):(g.info(` Output directory: ${e}`),g.info(` Files generated: ${u.length+1}`));}var Dy={devDependencies:{"@types/ioredis":"^5.0.0","@types/mongodb":"^4.0.7","@types/mssql":"^9.1.11","@types/pg":"^8.20.0","@types/sqlite3":"^5.1.0",esbuild:"^0.28.0",ioredis:"^5.10.1",mongodb:"^7.1.1",mssql:"^12.2.1",mysql2:"^3.20.0",pg:"^8.20.0",sqlite3:"^6.0.1",typescript:"^6.0.2"}};var $y=()=>ae.existsSync(yt.join(process.cwd(),"yarn.lock"))?["yarn","add"]:ae.existsSync(yt.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add"]:ae.existsSync(yt.join(process.cwd(),"package-lock.json"))?["npm","install"]:ae.existsSync(yt.join(process.cwd(),"bun.lockb"))?["bun","add"]:ae.existsSync(yt.join(process.cwd(),"deno.lock"))?["deno","add"]:["npm","install"],Ay=async(i,t,e,r)=>{let n=Bg.createInterface({input:process.stdin,output:process.stdout}),o=e.join(", "),s=`Do you want to install the following dependencies using ${t}?
362
362
  ${o}
363
363
  (y/n): `;return new Promise(a=>{n.question(s,l=>{if(n.close(),l.toLowerCase()==="y"||l.toLowerCase()==="yes"){execSync(i,r),a(true);return}a(false);});})},pe=Dy.devDependencies,vy=async(i,t,e)=>{let r=En.includes(e)?[`typescript@${pe.typescript}`,`esbuild@${pe.esbuild}`]:[],n="";switch(e){case "mariadb":case "mysql":n=`mysql2@${pe.mysql2}`;break;case "cockroachdb":case "postgres":n=`pg@${pe.pg}`,r.push(`@types/pg@${pe["@types/pg"]}`);break;case "sqlite":n=`sqlite3@${pe.sqlite3}`,r.push(`@types/sqlite3@${pe["@types/sqlite3"]}`);break;case "mongo":n=`mongodb@${pe.mongodb}`,r.push(`@types/mongodb@${pe["@types/mongodb"]}`);break;case "redis":n=`ioredis@${pe.ioredis}`,r.push(`@types/ioredis@${pe["@types/ioredis"]}`);break;case "mssql":n=`mssql@${pe.mssql}`,r.push(`@types/mssql@${pe["@types/mssql"]}`);break;default:throw new Error(`Invalid database type: ${e}`)}if(n){let s=await Ay(`${i} ${t} ${n}`,i,[n],{stdio:"inherit"});s&&g.info("Driver dependency installed successfully"),s||g.info("Driver dependency installation skipped");}let o=i==="deno"?"--dev":"-D";if(r.length){let s=await Ay(`${i} ${t} ${r.join(" ")} ${o}`,i,r,{stdio:"inherit"});s&&g.info("Dev dependencies installed successfully"),s||g.info("Dev dependencies installation skipped");}};var En=["sqlite","mysql","postgres","mariadb","cockroachdb","mssql"],Bn=En.concat("mongodb","redis");async function Ge(i,t){let{default:e}=await ft(yt.resolve(process.cwd(),i));return e||(g.error(`The provided datasource file does not export a default export: ${i}`),process.exit(1)),Be.isSqlDataSource(e)||(g.error(`The provided datasource file does not export a valid SqlDataSource instance: ${i}`),process.exit(1)),e.isConnected||await e.connect(),e}function lu(i,t,e,r){let n=typeof e=="boolean"?i??e:i??e?.enabled??true,o=typeof e=="object"?e?.timeout:r,s=t?parseInt(t,10):o??3e4,a=typeof e=="object"&&e.customValue!==void 0?typeof e.customValue=="function"?e.customValue():e.customValue:"hysteria_migration_lock";return {enabled:n,timeout:s,key:a}}var Te=new Command;Te.command("init",{isDefault:false}).option("-t, --type [type]",`Type of the database to connect to, available types: ${Bn.join(", ")}`,void 0).description("Initialize the hysteria-orm with standard configuration, it will create a database if not exists and a migrations folder inside it if not exists, it will also create a index.ts file in the database folder").action(async i=>{let t=Bn.join(", ");i.type||(g.error(`Database type is required (-t|--type), available types: ${t}`),process.exit(1)),Bn.includes(i.type)||(g.error(`Invalid database type: ${i.type}, available types: ${Bn.join(", ")}`),process.exit(1)),g.info("Initializing hysteria-orm with standard configuration"),g.info(`Database type: ${i.type||"not specified (will use env DB_TYPE)"}`);let[e,r]=$y();g.info(`Package manager: ${e}`),g.info("Installing base dependencies"),await vy(e,r,i.type);let n=An.initTemplate(i.type);ae.existsSync("database")?g.info("database folder already exists, skipping"):ae.mkdirSync("database",{recursive:true}),ae.existsSync("database/index.ts")?g.info("database/index.ts file already exists, skipping"):ae.writeFileSync("database/index.ts",n),En.includes(i.type)&&!ae.existsSync("database/migrations")?ae.mkdirSync("database/migrations",{recursive:true}):g.info("database/migrations folder already exists or is not a sql database, skipping"),g.info("Initialization completed successfully");});Te.command("sql [sql]").alias("run:sql").option("-f, --file [path]","Path to the sql file",void 0).option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-o, --out [query]","File path to save the query result",void 0).option("-t, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).description("Run a sql file or a sql query directly from the command line for the given connection defined in the env file").action(async(i,t)=>{g.info("Starting SQL execution"),t?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1));let e=t?.file;!i&&!e&&(g.error("SQL query or file path is required"),process.exit(1)),i&&e&&(g.error("Cannot provide both sql query and file path"),process.exit(1));let r=await Ge(t.datasource,t?.tsconfigPath);if(i){g.info("Executing SQL query directly from command line");try{await $n(i,r,t?.out),g.info("SQL execution completed successfully"),process.exit(0);}catch(o){g.error(`SQL execution failed: ${o}`),process.exit(1);}}e||(g.error("No SQL statement or file provided"),process.exit(1)),g.info(`Reading SQL from file: ${e}`),e=yt.resolve(process.cwd(),e),ae.existsSync(e)||(g.error(`File not found: ${e}`),process.exit(1));let n=ae.readFileSync(e,"utf-8");g.info(`SQL file loaded successfully (${n.length} characters)`);try{await $n(n,r,t?.out),g.info("SQL file execution completed successfully"),process.exit(0);}catch(o){g.error(`SQL file execution failed: ${o}`),process.exit(1);}});Te.command("create:migration <name>").description("Create a new migration file, standard folder is migrations from the current directory you are now, you can change it in the env MIGRATION_PATH").option("-j, --javascript","Generate a javascript migration file instead of a default typescript one",false).option("-a, --alter","Generate a template for an alter table migration",false).option("-c, --create","Generate a template for a create table migration",false).option("-t, --table <table>","Specifies the target table name for the migration",false).action((i,t)=>{g.info(`Creating migration: ${i}`),g.info(`Migration options: javascript=${t.javascript}, alter=${t.alter}, create=${t.create}, table=${t.table||"not specified"}`),i||(g.error("Migration name is required"),process.exit(1)),t.alter&&t.create&&(g.error("Cannot use --alter and --create at the same time"),process.exit(1)),t.table&&!(t.create||t.alter)&&(g.error("Cannot use --table without --create or --alter"),process.exit(1));let e=t.alter?"alter":t.create?"create":"basic";g.info(`Migration mode: ${e}`),Mu(i,t.javascript,e,t.table||i);});Te.command("migrate [runUntil]").option("-c, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-m, --migration-path [migrationPath]","Path to the migrations",void 0).option("-t, --transactional","Runs all the pending migrations in a single transaction, only applies to postgres",true).option("-l, --lock","Acquire advisory lock before running migrations to prevent concurrent execution",true).option("--lock-timeout [lockTimeout]","Lock timeout in milliseconds for migration advisory lock acquisition",void 0).description("Run pending migrations, if runUntil is provided, it will run all migrations until the provided migration name").action(async(i,t)=>{t?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1));let e=await Ge(t.datasource,t?.tsconfigPath),r=t?.migrationPath||e.migrationConfig.path,n=t?.tsconfigPath||e.migrationConfig.tsconfig,o=t?.transactional??e.migrationConfig.transactional,s=lu(t?.lock,t?.lockTimeout,e.migrationConfig.lock,e.migrationConfig.lockTimeout),a=false;try{if(s.enabled){if(g.info("Acquiring migration lock"),a=await e.acquireLock(typeof s.key=="string"?s.key:String(s.key),s.timeout),!a)throw g.error("Failed to acquire migration lock. Another migration may be running."),new Error("Failed to acquire migration lock");g.info("Migration lock acquired successfully");}await Et(e,i,r,n,o);}catch(l){throw console.error(l),l}finally{s.enabled&&a&&(g.info("Releasing migration lock"),await e.releaseLock(typeof s.key=="string"?s.key:String(s.key))||g.warn("Failed to release migration lock")),await e.disconnect();}});Te.command("rollback [rollbackUntil]").option("-c, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-m, --migration-path [migrationPath]","Path to the migrations",void 0).option("-t, --transactional","Runs all the pending migrations in a single transaction, this does not apply to mysql since it does not support transactions inside schema changes",true).option("-l, --lock","Acquire advisory lock before running migrations to prevent concurrent execution",true).option("--lock-timeout [lockTimeout]","Lock timeout in milliseconds for migration advisory lock acquisition",void 0).description("Rollbacks every migration that has been run, if rollbackUntil is provided, it will rollback all migrations until the provided migration name").action(async(i,t)=>{t?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1));let e=await Ge(t.datasource,t?.tsconfigPath),r=t?.migrationPath||e.migrationConfig.path,n=t?.tsconfigPath||e.migrationConfig.tsconfig,o=t?.transactional??e.migrationConfig.transactional,s=lu(t?.lock,t?.lockTimeout,e.migrationConfig.lock,e.migrationConfig.lockTimeout),a=false;try{if(s.enabled){if(g.info("Acquiring migration lock"),a=await e.acquireLock(typeof s.key=="string"?s.key:String(s.key),s.timeout),!a)throw g.error("Failed to acquire migration lock. Another migration may be running."),new Error("Failed to acquire migration lock");g.info("Migration lock acquired successfully");}await rr(e,i,r,n,o);}catch(l){throw console.error(l),l}finally{s.enabled&&a&&(g.info("Releasing migration lock"),await e.releaseLock(typeof s.key=="string"?s.key:String(s.key))||g.warn("Failed to release migration lock")),await e.disconnect();}});Te.command("refresh").option("-f, --force","Drop all tables in the database before running the migrations instead of running the down migrations",false).option("-c, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-t, --transactional","Runs all the pending migrations in a single transaction, this does not apply to mysql since it does not support transactions inside schema changes",true).option("-l, --lock","Acquire advisory lock before running migrations to prevent concurrent execution",true).option("--lock-timeout [lockTimeout]","Lock timeout in milliseconds for migration advisory lock acquisition",void 0).option("-m, --migration-path [path]","Path to the migrations",void 0).description("Rollbacks every migration that has been run and then run the migrations").action(async i=>{let t=i?.force||false;i?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1));let e=await Ge(i.datasource,i?.tsconfigPath),r=i?.migrationPath||e.migrationConfig.path,n=i?.tsconfigPath||e.migrationConfig.tsconfig,o=i?.transactional??e.migrationConfig.transactional,s=lu(i?.lock,i?.lockTimeout,e.migrationConfig.lock,e.migrationConfig.lockTimeout),a=false;try{if(s.enabled){if(g.info("Acquiring migration lock for refresh operation"),a=await e.acquireLock(typeof s.key=="string"?s.key:String(s.key),s.timeout),!a)throw g.error("Failed to acquire migration lock. Another migration may be running."),new Error("Failed to acquire migration lock");g.info("Migration lock acquired successfully");}t?await Ln(e,!1,o):await rr(e,void 0,r,n,o),await Et(e,void 0,r,n,o);}catch(l){console.error(l);}finally{s.enabled&&a&&(g.info("Releasing migration lock"),await e.releaseLock(typeof s.key=="string"?s.key:String(s.key))||g.warn("Failed to release migration lock")),await e.disconnect();}});Te.command("generate:migrations").description("Generate a migration file based on the database schema and the models metadata, supported only for postgres, mysql, mariadb and cockroachdb").option("-c, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-f, --dry","Does not create a migration file but only outputs sql statements",false).option("-j, --javascript","Generate a javascript migration file instead of a default typescript one",false).option("-m, --migration-path [path]","Path to the migrations",void 0).option("-n, --name [name]","Name of the migration",void 0).option("-o, --output [mode]","Output mode: 'code' generates schema builder calls, 'raw' generates raw SQL (default: code)","code").action(async i=>{i?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1)),i?.name||(i.name="auto_generated_migration"),i.name=`${Date.now()}_${i.name}`;let t=await Ge(i.datasource,i?.tsconfigPath),e=i?.migrationPath||t.migrationConfig.path;["mysql","postgres","mariadb","cockroachdb"].includes(t.getDbType())||(g.error(`generate:migrations is not supported for ${t.getDbType()}, it's suggested to use manual migrations instead`),process.exit(1));try{let n=await rt.makeDiff(t);if((i.output==="raw"?"raw":"code")==="code"){let s=n.getCodeStatements();if(s.up.length||(g.info("No new changes detected between database schema and models metadata"),process.exit(0)),i.dry){console.log("// up()");for(let u of s.up)console.log(u);console.log(`
364
364
  // down()`);for(let u of s.down)console.log(u);process.exit(0);}ae.existsSync(e)||ae.mkdirSync(e,{recursive:!0});let a=await nr.generate(s,"code"),l=i?.javascript?".js":".ts";ae.writeFileSync(`${e}/${i?.name}${l}`,a),g.info(`Migration file created successfully: ${i?.name}${l}`);}else {let s=n.getSqlStatements();if(s.length||(g.info("No new changes detected between database schema and models metadata"),process.exit(0)),i.dry){for(let u of s)console.log(u);process.exit(0);}ae.existsSync(e)||ae.mkdirSync(e,{recursive:!0});let a=await nr.generate(s,"raw"),l=i?.javascript?".js":".ts";ae.writeFileSync(`${e}/${i?.name}${l}`,a),g.info(`Migration file created successfully: ${i?.name}${l}`);}await t.disconnect(),process.exit(0);}catch(n){console.error(n),await t.disconnect(),process.exit(1);}});Te.command("sync").description("Sync the database schema with the models metadata by computing a diff and applying the SQL statements directly, supported only for postgres, mysql, mariadb and cockroachdb").option("-c, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-f, --dry","Does not apply changes but only outputs the SQL statements that would be executed",false).option("-t, --transactional","Runs all the sync statements in a single transaction",false).action(async i=>{i?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1));let t=await Ge(i.datasource,i?.tsconfigPath);["mysql","postgres","mariadb","cockroachdb"].includes(t.getDbType())||(g.error(`sync is not supported for ${t.getDbType()}, it's suggested to use manual migrations instead`),await t.disconnect(),process.exit(1));try{let n=(await rt.makeDiff(t)).getSqlStatements();if(n.length||(g.info("No new changes detected between database schema and models metadata"),await t.disconnect(),process.exit(0)),i.dry){g.info(`${n.length} SQL statement(s) would be executed:`);for(let o of n)console.log(o);await t.disconnect(),process.exit(0);}await t.syncSchema({transactional:i?.transactional??!1}),g.info("Schema sync completed successfully"),await t.disconnect(),process.exit(0);}catch(r){console.error(r),await t.disconnect(),process.exit(1);}});Te.command("create:seeder <name>").description("Create a new seeder file").option("-j, --javascript","Generate a javascript seeder file instead of a default typescript one",false).option("-s, --seeder-path [path]","Path to the seeders",void 0).action((i,t)=>{g.info(`Creating seeder: ${i}`),g.info(`Seeder options: javascript=${t.javascript}`),i||(g.error("Seeder name is required"),process.exit(1)),fy(i,t.javascript,t.seederPath);});Te.command("seed").description("Run database seeders from folder or specific files").option("-c, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-s, --seeder-path [path]","Path to seeder folder or file (can be specified multiple times or comma-separated)",(i,t=[])=>[...t,i]).action(async i=>{g.info("Starting seeder execution"),i?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1));let t=await Ge(i.datasource,i?.tsconfigPath),e;i?.seederPath&&i.seederPath.length>0?e=i.seederPath.flatMap(n=>n.split(",").map(o=>o.trim())):e=[t.seederConfig.path];let r=i?.tsconfigPath||t.seederConfig.tsconfig;try{await yy(t,e,r),await t.disconnect(),g.info("Seeding completed successfully"),process.exit(0);}catch(n){console.error(n),await t.disconnect(),process.exit(1);}});Te.command("db:pull").description("Generate TypeScript model files from database schema introspection").option("-d, --datasource [path]","Path to SqlDataSource (default export)",void 0).option("-o, --out [path]","Output directory for generated models","./database/models").option("--naming [convention]","Naming convention for model names (camel, snake, pascal)","camel").option("--dry","Preview generated code without writing files",false).option("-c, --tsconfig [tsconfigPath]","Path to the tsconfig.json file, defaults to ./tsconfig.json",void 0).action(async i=>{i?.datasource||(g.error("SqlDataSource file path is required (-d|--datasource)"),process.exit(1));let t=["camel","snake","pascal"],e=i?.naming||"camel";t.includes(e)||(g.error(`Invalid naming convention: ${e}. Must be one of: ${t.join(", ")}`),process.exit(1));let r=await Ge(i.datasource,i?.tsconfig);try{await au(r,{outDir:i?.out||"./database/models",naming:e,dry:i?.dry||!1}),await r.disconnect(),process.exit(0);}catch(n){console.error(n),await r.disconnect(),process.exit(1);}});Te.parse(process.argv);