hysteria-orm 11.0.2 → 11.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import ne from'fs';import tt from'path';import Ml from'fs/promises';import {format}from'sql-formatter';import {highlight}from'sql-highlight';import {createRequire}from'module';import {pathToFileURL}from'url';import xe,{privateDecrypt,publicEncrypt,randomBytes}from'crypto';import {PassThrough,Readable}from'stream';import {performance}from'perf_hooks';import {execSync}from'child_process';import eh from'readline';var Sf=Object.defineProperty;var gl=i=>{throw TypeError(i)};var bl=(i,t,e,r)=>{for(var o=void 0,n=i.length-1,s;n>=0;n--)(s=i[n])&&(o=(s(t,e,o))||o);return o&&Sf(t,e,o),o};var Cf=(i,t,e)=>t.has(i)||gl("Cannot "+e);var Tl=(i,t,e)=>t.has(i)?gl("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e);var wl=(i,t,e)=>(Cf(i,t,"access private method"),e);var N=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}},ft=class extends N{constructor(t){super("ValidationError","VALIDATION_ERROR"),this.errors=t;}};var re=class{constructor(t){this.options=t;}static async createDriver(t){throw new N("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var K=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var yt=class yt extends re{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new yt(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new K("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new K("mongodb");return new yt(this.mongoClient)}};yt.mongoClient=null;var jt=yt;var ht=class ht extends re{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new ht(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new K("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new K("mssql");return new ht(this.mssqlClient)}};ht.mssqlClient=null;var Wt=ht;var gt=class gt extends re{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 K("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new K("mysql2");return new gt(this.mysqlClient)}};gt.mysqlClient=null;var Ut=gt;var bt=class bt extends re{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new bt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new K("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new K("oracledb");return new bt(this.oracledbClient)}};bt.oracledbClient=null;var Ft=bt;var Tt=class Tt extends re{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Tt(this.pgClient);let e=await import('pg').catch(()=>{throw new K("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new K("pg");return new Tt(this.pgClient)}};Tt.pgClient=null;var Vt=Tt;var wt=class wt extends re{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new wt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new K("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new K("sqlite3");return new wt(this.sqlite3Client)}};wt.sqlite3Client=null;var Jt=wt;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 Ut.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Vt.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Jt.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await jt.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await Wt.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await Ft.createDriver(),this.oracledbDriver;default:throw new N(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;case "oracledb":return this.oracledbDriver;default:return null}}};me.mysqlDriver=null,me.pgDriver=null,me.sqliteDriver=null,me.mssqlDriver=null,me.oracledbDriver=null,me.mongodbDriver=null;var E={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},Mf=()=>{if(!ne.existsSync(".env"))return E;try{ne.readFileSync(".env","utf8").split(`
2
+ import {Command}from'commander';import ne from'fs';import tt from'path';import Ml from'fs/promises';import {format}from'sql-formatter';import {highlight}from'sql-highlight';import {createRequire}from'module';import {pathToFileURL}from'url';import xe,{randomUUID,privateDecrypt,publicEncrypt,randomBytes}from'crypto';import {PassThrough,Readable}from'stream';import {performance}from'perf_hooks';import {execSync}from'child_process';import th from'readline';var Sf=Object.defineProperty;var gl=i=>{throw TypeError(i)};var bl=(i,t,e,r)=>{for(var o=void 0,n=i.length-1,s;n>=0;n--)(s=i[n])&&(o=(s(t,e,o))||o);return o&&Sf(t,e,o),o};var Cf=(i,t,e)=>t.has(i)||gl("Cannot "+e);var Tl=(i,t,e)=>t.has(i)?gl("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e);var wl=(i,t,e)=>(Cf(i,t,"access private method"),e);var N=class extends Error{constructor(t,e,r){super(t+" - "+e),this.code=e,this.caller=t,this.error=r;}},ft=class extends N{constructor(t){super("ValidationError","VALIDATION_ERROR"),this.errors=t;}};var re=class{constructor(t){this.options=t;}static async createDriver(t){throw new N("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var K=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var yt=class yt extends re{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new yt(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new K("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new K("mongodb");return new yt(this.mongoClient)}};yt.mongoClient=null;var jt=yt;var ht=class ht extends re{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new ht(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new K("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new K("mssql");return new ht(this.mssqlClient)}};ht.mssqlClient=null;var Wt=ht;var gt=class gt extends re{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 K("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new K("mysql2");return new gt(this.mysqlClient)}};gt.mysqlClient=null;var Ut=gt;var bt=class bt extends re{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new bt(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new K("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new K("oracledb");return new bt(this.oracledbClient)}};bt.oracledbClient=null;var Ft=bt;var Tt=class Tt extends re{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Tt(this.pgClient);let e=await import('pg').catch(()=>{throw new K("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new K("pg");return new Tt(this.pgClient)}};Tt.pgClient=null;var Vt=Tt;var wt=class wt extends re{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new wt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new K("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new K("sqlite3");return new wt(this.sqlite3Client)}};wt.sqlite3Client=null;var Jt=wt;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 Ut.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await Vt.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Jt.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await jt.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await Wt.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await Ft.createDriver(),this.oracledbDriver;default:throw new N(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;case "oracledb":return this.oracledbDriver;default:return null}}};me.mysqlDriver=null,me.pgDriver=null,me.sqliteDriver=null,me.mssqlDriver=null,me.oracledbDriver=null,me.mongodbDriver=null;var E={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},Mf=()=>{if(!ne.existsSync(".env"))return E;try{ne.readFileSync(".env","utf8").split(`
3
3
  `).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":E.DB_TYPE||(E.DB_TYPE=s);break;case "DB_HOST":E.DB_HOST||(E.DB_HOST=s);break;case "DB_PORT":E.DB_PORT||(E.DB_PORT=s);break;case "DB_USER":E.DB_USER||(E.DB_USER=s);break;case "DB_PASSWORD":E.DB_PASSWORD||(E.DB_PASSWORD=s);break;case "DB_DATABASE":E.DB_DATABASE||(E.DB_DATABASE=s);break;case "MIGRATION_PATH":E.MIGRATION_PATH||(E.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":E.REDIS_HOST||(E.REDIS_HOST=s);break;case "REDIS_PORT":E.REDIS_PORT||(E.REDIS_PORT=s);break;case "REDIS_USERNAME":E.REDIS_USERNAME||(E.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":E.REDIS_PASSWORD||(E.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":E.REDIS_DATABASE||(E.REDIS_DATABASE=s);break;case "MONGO_URL":E.MONGO_URL||(E.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":E.MSSQL_TRUST_SERVER_CERTIFICATE||(E.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return E}},P=Mf();var _f=async i=>(await me.getDriver(i)).client,He=async(i,t)=>{let e=await _f(i);switch(i){case "mariadb":case "mysql":let r=t;return e.createPool({host:r.host,port:r.port,user:r.username,password:r.password,database:r.database,...r?.driverOptions});case "postgres":case "cockroachdb":let s=t,a=e;return new a.Pool({host:s.host,port:s.port,user:s.username,password:s.password,database:s.database,...s?.driverOptions});case "sqlite":let u=e,d=t,m=d?.database;return new u.Database(m,d?.driverOptions?.mode??void 0,D=>{if(D)throw new N("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let p=e,f=t,{options:y,...T}=f.driverOptions??{},b=new p.ConnectionPool({server:f.host??"localhost",port:f.port,database:f.database,user:f.username,password:f.password,...T,options:{trustServerCertificate:P.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...y,abortTransactionOnError:false,enableImplicitTransactions:false}});return await b.connect(),b;case "oracledb":let q=e,R=t,M=`${R.host}/${R.database}`;return await q.createPool({user:R.username,password:R.password,connectString:M,...R.driverOptions});default:throw new N("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var Nt=i=>{switch(i){case "mysql":return "mysql";case "mariadb":return "mariadb";case "postgres":case "cockroachdb":return "postgresql";case "sqlite":return "sqlite";case "mssql":return "transactsql";case "oracledb":return "plsql";default:return "sql"}},Ht=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)},ze=(i,t)=>{let e=i;for(let r=0;r<t.length&&e.includes("?");r++)e=e.replace(/\?/,Ht(t[r]));for(let r=0;r<t.length;r++){let o=new RegExp(`\\$${r+1}(?!\\d)`,"g");e=e.replace(o,Ht(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`\\@${r+1}(?!\\d)`,"g");e=e.replace(o,Ht(t[r]));}for(let r=0;r<t.length;r++){let o=new RegExp(`:${r+1}(?!\\d)`,"g");e=e.replace(o,Ht(t[r]));}return e},Ye=(i,t)=>t?i==="mysql"||i==="mariadb"?t.code==="ER_NO_SUCH_TABLE"||t.errno===1146:i==="postgres"||i==="cockroachdb"?t.code==="42P01":i==="sqlite"?/no such table/i.test(String(t.message||"")):i==="mssql"?t.number===208:i==="oracledb"?t.errorNum===942:false:false,Ge=(i,t)=>{let e=i.getDbType(),r;try{r=format(t,{...i.inputDetails.queryFormatOptions,language:Nt(e)});}catch{try{r=format(t,{...i.inputDetails.queryFormatOptions});}catch{r=t;}}return r};var ql={info:0,warn:1,error:2};function zt(i){return i?i===true?{level:"info",logQueries:true}:{level:i.level??"info",logQueries:i.logQueries??true,customLogger:i.customLogger}:null}function Of(i,t="info"){let e=zt(i);if(!e)return false;let r=e.level??"info";return ql[t]>=ql[r]}function Af(i){let t=zt(i);return t?t.logQueries??true:false}var Ze={info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",reset:"\x1B[0m"};function $f(){let i=new Date,t=e=>e.toString().padStart(2,"0");return `${i.getFullYear()}-${t(i.getMonth()+1)}-${t(i.getDate())} ${t(i.getHours())}:${t(i.getMinutes())}:${t(i.getSeconds())}`}function eo(i,t){let e=$f(),r=i.toUpperCase();return i==="error"?`${Ze.error}[${r}] ${e}
4
4
  ${t}${Ze.reset}
5
5
  `:i==="warn"?`${Ze.warn}[${r}] ${e}
@@ -314,7 +314,7 @@ ORDER BY ordinal_position`,bindings:[]}}},hm=new Vi;var Ji=class{toSql(t){let e=
314
314
  FROM pragma_table_info('${t.table}')
315
315
  WHERE pk > 0
316
316
  ORDER BY pk`,bindings:[]}}},mp=new ja;var Wa=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},pp=new Wa;var Ua=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new w(this.model,"sqlite").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new w(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new w(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},fp=new Ua;var Fa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=ae.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},yp=new Fa;var Va=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new h(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},hp=new Va;var Ja=class{toSql(t){let e=t,r=new w(this.model,"sqlite"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},gp=new Ja;var Ha=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let u=e.values[l];return u instanceof I?`${r.formatStringColumn("sqlite",a)} = ${u.rawValue}`:(n.push(u),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},bp=new Ha;var za=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new h(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("sqlite",t):t}},Tp=new za;var Ya=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new w(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},wp=new Ya;var Ga=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},Np=new Ga;var Za=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 w(this.model,"sqlite"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new w(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},Sp=new Za;var Xa=class{toSql(t){let e=t,r=new w(this.model,"sqlite"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},qp=new Xa;var Cp={mssql:{alter_table:{add_column:El,add_constraint:vl,add_primary_key:kl,alter_column_type:Bl,alter_table:Ql,drop_column:Kl,drop_constraint:Ll,drop_default:jl,drop_not_null:Wl,drop_primary_key:Ul,rename_column:Fl,rename_table:Vl,set_default:Jl,set_not_null:Hl,set_table_options:zl},column:{column_type:Yl},constraint:{after:Gl,constraint:Zl},create_table:{create_table:Xl},delete:{delete:eu},distinct:{distinct:tu,distinct_on:ru},drop_table:{drop_table:ou},extension:{create_extension:nu},from:{from:su},group_by:{group_by:iu},having:{having:au},index_op:{create_index:lu,drop_index:uu},insert:{insert:du},join:{join:cu},limit:{limit:mu},lock:{lock:pu},offset:{offset:fu},on_duplicate:{on_duplicate:yu},order_by:{order_by:hu},raw:{raw:gu},schema:{check_constraint_info:bu,foreign_key_info:Tu,index_info:wu,primary_key_info:Nu,table_info:Su},select:{select:qu,select_json:Cu},truncate:{truncate:Mu},union:{union:_u},update:{update:Ru},where:{where:xu,where_group:Ou,where_json:Au,where_subquery:$u},with:{with:Du}},mysql:{alter_table:{add_column:Iu,add_constraint:Pu,add_primary_key:Eu,alter_column_type:vu,alter_table:ku,drop_column:Bu,drop_constraint:Qu,drop_default:Ku,drop_not_null:Lu,drop_primary_key:ju,rename_column:Wu,rename_table:Uu,set_default:Fu,set_not_null:Vu,set_table_options:Ju},column:{column_type:Hu},constraint:{after:zu,constraint:Yu},create_table:{create_table:Gu},delete:{delete:Zu},distinct:{distinct:Xu,distinct_on:ed},drop_table:{drop_table:td},extension:{create_extension:rd},from:{from:od},group_by:{group_by:nd},having:{having:sd},index_op:{create_index:id,drop_index:ad},insert:{insert:ld},join:{join:ud},limit:{limit:dd},lock:{lock:cd},offset:{offset:md},on_duplicate:{on_duplicate:pd},order_by:{order_by:fd},raw:{raw:yd},schema:{check_constraint_info:hd,foreign_key_info:gd,index_info:bd,primary_key_info:Td,table_info:wd},select:{select:Nd,select_json:Sd},truncate:{truncate:qd},union:{union:Cd},update:{update:Md},where:{where:_d,where_group:Rd,where_json:xd,where_subquery:Od},with:{with:Ad}},oracledb:{alter_table:{add_column:$d,add_constraint:Dd,add_primary_key:Id,alter_column_type:Pd,alter_table:Ed,drop_column:vd,drop_constraint:kd,drop_default:Bd,drop_not_null:Qd,drop_primary_key:Kd,rename_column:Ld,rename_table:jd,set_default:Wd,set_not_null:Ud,set_table_options:Fd},column:{column_type:Vd},constraint:{after:Jd,constraint:Hd},create_table:{create_table:zd},delete:{delete:Yd},distinct:{distinct:Gd,distinct_on:Zd},drop_table:{drop_table:Xd},extension:{create_extension:ec},from:{from:tc},group_by:{group_by:rc},having:{having:oc},index_op:{create_index:nc,drop_index:sc},insert:{insert:ic},join:{join:ac},limit:{limit:lc},lock:{lock:uc},offset:{offset:dc},on_duplicate:{on_duplicate:cc},order_by:{order_by:mc},raw:{raw:pc},schema:{check_constraint_info:fc,foreign_key_info:yc,index_info:hc,primary_key_info:gc,table_info:bc},select:{select:Tc,select_json:wc},truncate:{truncate:Nc},union:{union:Sc},update:{update:qc},where:{where:Cc,where_group:Mc,where_json:_c,where_subquery:Rc},with:{with:xc}},postgres:{alter_table:{add_column:Oc,add_constraint:Ac,add_primary_key:$c,alter_column_type:Dc,alter_table:Ic,drop_column:Pc,drop_constraint:Ec,drop_default:vc,drop_not_null:kc,drop_primary_key:Bc,rename_column:Qc,rename_table:Kc,set_default:Lc,set_not_null:jc,set_table_options:Wc},column:{column_type:Uc},constraint:{after:Fc,constraint:Vc},create_table:{create_table:Jc},delete:{delete:Hc},distinct:{distinct:zc,distinct_on:Yc},drop_table:{drop_table:Gc},extension:{create_extension:Zc},from:{from:Xc},group_by:{group_by:em},having:{having:tm},index_op:{create_index:rm,drop_index:om},insert:{insert:nm},join:{join:sm},limit:{limit:im},lock:{lock:am},offset:{offset:lm},on_duplicate:{on_duplicate:um},order_by:{order_by:dm},raw:{raw:cm},schema:{check_constraint_info:mm,foreign_key_info:pm,index_info:fm,primary_key_info:ym,table_info:hm},select:{select:gm,select_json:bm},truncate:{truncate:Tm},union:{union:wm},update:{update:Nm},where:{where:Sm,where_group:qm,where_json:Cm,where_subquery:Mm},with:{with:_m}},sqlite:{alter_table:{add_column:Rm,add_constraint:xm,alter_column_type:Om,alter_table:Am,drop_column:$m,drop_constraint:Dm,drop_default:Im,drop_not_null:Pm,drop_primary_key:Em,rename_column:vm,rename_table:km,set_default:Bm,set_not_null:Qm,set_table_options:Km},column:{column_type:Lm},constraint:{after:jm,constraint:Wm},create_table:{create_table:Um},delete:{delete:Fm},distinct:{distinct:Vm,distinct_on:Jm},drop_table:{drop_table:Hm},extension:{create_extension:zm},from:{from:Ym},group_by:{group_by:Gm},having:{having:Zm},index_op:{create_index:Xm,drop_index:ep},insert:{insert:tp},join:{join:rp},limit:{limit:op},lock:{lock:np},offset:{offset:sp},on_duplicate:{on_duplicate:ip},order_by:{order_by:ap},raw:{raw:lp},schema:{check_constraint_info:up,foreign_key_info:dp,index_info:cp,primary_key_info:mp,table_info:pp},select:{select:fp,select_json:yp},truncate:{truncate:hp},union:{union:gp},update:{update:bp},where:{where:Tp,where_group:wp,where_json:Np,where_subquery:Sp},with:{with:qp}}};var w=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(M=>!!M&&M.folder==="distinctOn"),n=!o&&t.find(M=>!!M&&M.folder==="distinct"),s=this.dbType==="mssql"?t.find(M=>!!M&&M.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(M=>M!==null&&M.folder!=="distinct"&&M.folder!=="distinctOn"),u=l.some(M=>M.folder==="offset"),d=l.some(M=>M.folder==="order_by"),m=l.find(M=>M.folder==="limit"),c=l.find(M=>M.folder==="offset"),p=this.dbType==="mssql"&&m&&!u&&!d,f=this.dbType==="mssql"&&!p&&(m||c),y=this.dbType==="oracledb"&&(m||c),T=[],b=[],q=null;p&&m&&b.push(m.limit);for(let M=0;M<l.length;M++){let O=l[M];if(p&&O.folder==="limit"||f&&(O.folder==="limit"||O.folder==="offset")||y&&(O.folder==="limit"||O.folder==="offset"))continue;O.currParamIndex=e+b.length;let D=Cp[this.mapCommonDbType(this.dbType)][O.folder][O.file];if(!D)throw new Error(`Interpreter not found for ${this.dbType} ${O.keyword}`);D.model=this.model;let _=D.toSql(O);if(!_.sql||!_.sql.trim().length)continue;let v=l[M+1],$=!v||v.keyword!==O.keyword?"":v.chainsWith;if(O.folder==="lock"||O.folder==="on_duplicate"||O.folder==="schema"){T.push(`${_.sql}${$}`),b.push(..._.bindings),q=O.keyword;continue}if(q!==O.keyword||O.canKeywordBeSeenMultipleTimes){if(r)T.push(`${_.sql}${$}`);else {let V=O.keyword;if(O.folder==="with"&&this.dbType!=="mssql"){let ee=M,Oe=false;for(;ee<l.length&&l[ee].keyword===O.keyword;){let Ce=l[ee];if(Ce.folder==="with"&&Ce.clause==="recursive"){Oe=true;break}ee++;}Oe&&(V=`${V} recursive`);}if(V==="select"){let ee=p?`top (@${e}) `:"";if(o){let Oe=Array.isArray(o.columns)?o.columns.join(", "):"";T.push(`select ${ee}distinct on (${Oe}) ${_.sql}${$}`);}else n?T.push(`select ${ee}distinct ${_.sql}${$}`):T.push(`select ${ee}${_.sql}${$}`);}else V==="from"&&a?T.push(`${V} ${_.sql}${a}${$}`):T.push(`${V} ${_.sql}${$}`);}q=O.keyword;}else T.push(`${_.sql}${$}`);b.push(..._.bindings);}if(f){d||T.push("order by (select null)");let M=c?.offset??0;b.push(M);let D=`offset @${e+b.length-1} rows`;if(m){b.push(m.limit);let _=e+b.length-1;D+=` fetch next @${_} rows only`;}T.push(D);}if(y){d||T.push("order by null");let M=c?.offset??0;b.push(M);let D=`offset :${e+b.length-1} rows`;if(m){b.push(m.limit);let _=e+b.length-1;D+=` fetch next :${_} rows only`;}T.push(D);}return {sql:T.join(" "),bindings:b}}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 or=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var nr=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var sr=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var ir=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var ar=class extends S{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var lr=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var pe=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var nt=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var ur=class extends S{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var fe=class extends S{constructor(e,r=[],o=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=o;}};var dr=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var ye=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var Mt=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var cr=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var st=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var mr=class extends S{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var pr=class extends S{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var fr=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var Ke=class extends S{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var F=class extends S{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var yr=class extends S{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var hr=class extends S{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var gr=class extends S{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var br=class extends S{constructor(e,r,o,n=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=o,this.unique=n;}};var Tr=class extends S{constructor(e,r,o){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=o??false;}};var it=class extends S{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};function ry(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 wr=Symbol("columns"),at=Symbol("primaryKey"),el=Symbol("relations"),Mp=Symbol("indexes"),_p=Symbol("uniques"),Rp=Symbol("checks"),tl=i=>`${ry(i)}_id`,rl=(i,t)=>`idx_${i}_${t}`,he=(i,t)=>`uq_${i}_${t}`,Z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,ge=(i,t)=>`pk_${i}_${t}`;var k=class extends S{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false,this.unsigned=o.unsigned,this.zerofill=o.zerofill;}};var _t=class extends S{constructor(e,r=false,o=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=o;}};var Le=class extends S{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var lt=class extends S{constructor(e,r,o){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=o,this.clause=e;}};var De=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Nr=class extends S{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var Sr=class extends De{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=ge(this.tableName,C(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new F("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new F("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??Z(this.tableName??"",C(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new F("foreign_key",{columns:[C(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new F("foreign_key",{columns:[C(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}unsigned(){return this.columnNode.unsigned=true,this}zerofill(){return this.columnNode.zerofill=true,this}notNullable(){return this.nodes.push(new F("not_null",{columns:[C(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new F("null",{columns:[C(this.columnNode.column)]})),this}default(t){let e;return t instanceof I?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new F("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new F("unique",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??he(this.tableName??"",C(this.columnNode.column))})),this):(this.namedConstraints.push(new F("unique",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName||he(this.tableName??"",C(this.columnNode.column))})),this)}check(t,e){let r=C(this.columnNode.column),o=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new F("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new F("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new Nr(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.nodes.push(new F("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var je=class extends De{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new Sr(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new I(e)}char(e,r=1){let o=new k(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new k(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new k(e,r);return this.build(o)}longtext(e){return this.text(e,"longtext")}mediumtext(e){return this.text(e,"mediumtext")}tinytext(e){return this.text(e,"tinytext")}uuid(e){let r=new k(e,"uuid");return this.build(r)}ulid(e){let r=new k(e,"ulid");return this.build(r)}integer(e,r=255){let o=new k(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new k(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new k(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new k(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new k(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new k(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new k(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new k(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new k(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new k(e,"numeric",{precision:r,scale:o});return this.build(n)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let o=new k(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new k(e,"time",{precision:r});return this.build(o)}year(e){let r=new k(e,"year");return this.build(r)}datetime(e,r){let o=new k(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}timestamp(e,r){let o=new k(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}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 o=new k(e,"varbinary",{length:r});return this.build(o)}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 o=new k(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new k(e,r,{length:o});return this.build(n)}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 qr=class extends De{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new I(t)}addColumn(t){let e=[],r=new je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(m=>m.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(m=>{let c=m;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),u=new lr(a);u.inlineConstraints=l,this.nodes.push(u),o.getNodes().filter(m=>{let c=m;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(m=>{this.nodes.push(new pe(m));});}alterColumn(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(p=>p.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=C(s.column),l=o.getNodes().find(p=>p.constraintType==="null"),d=o.getNodes().find(p=>p.constraintType==="not_null")||l,m=o.getNodes().find(p=>p.constraintType==="default"),c={};d&&(c.nullable=d.constraintType==="null"),m&&(m.defaultValue===void 0||m.defaultValue===null||m.defaultValue==="NULL"?c.dropDefault=true:c.default=m.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(c.collate=s.collate),this.nodes.push(new ur(C(a),s,c)),d&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(d.constraintType==="not_null"?this.nodes.push(new fr(C(a))):d.constraintType==="null"&&this.nodes.push(new cr(C(a)))),m&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(m.defaultValue===void 0||m.defaultValue===null||m.defaultValue==="NULL"?this.nodes.push(new Mt(C(a))):this.nodes.push(new pr(C(a),m.defaultValue))),o.getNodes().forEach(p=>{let f=p;switch(f.constraintType){case "primary_key":this.addPrimaryKey(C(a));break;case "unique":this.unique(C(a),{constraintName:f.constraintName});break;case "foreign_key":this.foreignKey(C(a),f.references?.table??"",C(f.references?.columns?.[0]??""),{constraintName:f.constraintName,onDelete:f.onDelete,onUpdate:f.onUpdate});break}});}dropColumn(t){this.nodes.push(new dr(t));}renameColumn(t,e){this.nodes.push(new mr(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Mt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new nt([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pe(new F(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pe(new F("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??Z(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new pe(new F("unique",{columns:[t],constraintName:e?.constraintName??he(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new N("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 ye(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new N("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??he(this.table,t);this.nodes.push(new ye(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ye(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new N("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new st(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",o=this.sqlType==="mssql",n=this.sqlType==="oracledb";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new Ke(t)):r?this.nodes.push(new Ke(t)):o?this.nodes.push(new Ke(t)):n&&this.nodes.push(new Ke(t)),this)}};var le=class{constructor(t){if(this.sqlType=t||P.DB_TYPE,!this.sqlType)throw new N("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new I(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!ne.existsSync(t))throw new N("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=tt.basename(t),r=tt.extname(e);if(r!==".sql"&&r!==".txt")throw new N("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=ne.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new je(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new w({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?o.getMysqlOptions()||{}:{}},l=new yr(t,n,o.getNamedConstraints(),r?.ifNotExists,a),u=s.parse([l]).sql,d=u.startsWith("create table")?u:`create table ${u}`;this.rawQuery(d),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new qr(t,r,this.sqlType);if(e(o),!r.length)return;let n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"}),s=[],a=()=>{if(!s.length)return;let u=new fe(t,s),d=n.parse([u]).sql;if(!d||!d.trim())return;let m=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(m),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 hr(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new fe(t,[new ot(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new it(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r={}){Array.isArray(e)||(e=[e]);let o=r.constraintName||rl(t,e.join("_")),n=new br(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new Tr(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new nt(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addUnique(t,e,r){let o=Array.isArray(e)?e:[e],n=r?.constraintName??he(t,o.join("_")),s=new F("unique",{columns:o,constraintName:n}),a=new fe(t,[new pe(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=Z(t,e,r),n=new ye(o),s=new fe(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?he(t,e.join("_")):he(t,e),n=r?.constraintName??o,s=new ye(n),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 F(...e),o=new fe(t,[new pe(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new ye(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addCheck(t,e,r){let o=r?.constraintName??`chk_${t}_custom`.substring(0,63),n=new F("check",{checkExpression:e,constraintName:o}),s=new fe(t,[new pe(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new ye(e),o=new fe(t,[r]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}createExtension(t,e=true){let r=new gr(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(o=>o.folder==="column"&&o.autoUpdate===true).map(o=>C(o.column));for(let o of r){let n=this.getAutoUpdateTriggerSql(t,o);for(let s of n)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];case "oracledb":return [`CREATE OR REPLACE TRIGGER "${r}" BEFORE UPDATE ON "${t}" FOR EACH ROW BEGIN :NEW."${e}" := CURRENT_TIMESTAMP; END;`];default:return []}}generateAstInstance(t){return new w(t,this.sqlType)}};var Cr,Ap,Rt=class{constructor(t,e){Tl(this,Cr);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new le(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=wl(this,Cr,Ap).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(`;
317
- `)}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"}};Cr=new WeakSet,Ap=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 we=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var Mr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===n.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(u=>u.table===n.table);if(l){let u=l.getColumns().find(d=>d.databaseName===n.column);if(u){u.isPrimary&&a.push(`pk.${n.table}`);let d=l.getRelations();for(let m of d)m.columnName===u.columnName&&a.push(`fk.${n.table}.${m.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let u of l)s(u);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),u=t.relationsToDrop?.find(d=>d.table===a&&d.relation.name===l);u&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:u,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(u)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let u of l)u.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):u.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(u=>u.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var _r=class _r{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new Mr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,o=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),n=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...o].filter(l=>n.has(l)));return e.filter(l=>{let u=r(l);return u?!(s.has(u)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new le(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===o.table)?.getColumns().find(u=>u.columnName===o.columns[0])?.primaryKeyConstraintName||ge(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,u=>{let d=a||ge(o.table,o.columns[0]);u.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}for(let o of t.checksToDrop||[]){let n=new le(this.sql.getDbType());n.dropCheck(o.table,o.name);let s=n.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}for(let o of t.checksToAdd||[]){let n=new le(this.sql.getDbType());n.addCheck(o.table,o.expression,{constraintName:o.name});let s=n.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=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 n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,Z(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=C(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s;if(Array.isArray(r.type))s=e.enum(o[0],r.type);else if(typeof r.type=="string"&&_r.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...o);else if(typeof r.type=="string")s=e.custom(o[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||ge(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new le(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=C(t.relation.manyToManyOptions.throughModel),r=C(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let o=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,n=C(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),p=c.primaryKey,y=c.getColumns().find(T=>T.columnName===p);if(y)n=y.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=H(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let p=c.getColumns(),f=p.find(y=>y.columnName===n);if(f)n=f.databaseName;else {let y=c.primaryKey||"id",T=p.find(b=>b.columnName===y);if(T)n=T.databaseName;else {let b=c?.databaseCaseConvention||"preserve";n=H(n||y,b);}}}else {let p=c.primaryKey||"id",y=c.getColumns().find(T=>T.columnName===p);if(y)n=y.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=H(p,T);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(c=>c.columnName===l);if(u)l=u.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=H(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(p=>p.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=H(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,p=C(c),f=a.find(y=>y.columnName===p);if(f)l=f.databaseName;else {let y=s?.databaseCaseConvention||"preserve";l=H(p,y);}}let d=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,c=>{let p=o||Z(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:d,onUpdate:m});}).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," "))}))}};_r.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var xt=_r;var xr=class xr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],o=null,n={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==o&&(o=s.phase,e.length>0&&e.push(""),e.push(`// ${n[o]}`));let{up:a,down:l}=this.generateOperationCode(s);a&&e.push(...a),l&&r.push(...l);}return {up:e,down:r}}generateOperationCode(t){switch(t.type){case "CREATE_TABLE":return this.generateCreateTableCode(t);case "ADD_COLUMN":return this.generateAddColumnCode(t);case "MODIFY_COLUMN":return this.generateModifyColumnCode(t);case "DROP_COLUMN":return this.generateDropColumnCode(t);case "CREATE_INDEX":return this.generateCreateIndexCode(t);case "DROP_INDEX":return this.generateDropIndexCode(t);case "ADD_FOREIGN_KEY":return this.generateAddForeignKeyCode(t);case "DROP_FOREIGN_KEY":return this.generateDropForeignKeyCode(t);case "ADD_UNIQUE_CONSTRAINT":return this.generateAddUniqueCode(t);case "DROP_CONSTRAINT":return this.generateDropConstraintCode(t);case "ADD_CHECK_CONSTRAINT":return this.generateAddCheckCode(t);case "ADD_PRIMARY_KEY":return this.generateAddPrimaryKeyCode(t);case "DROP_TABLE":return this.generateDropTableCode(t);case "MODIFY_PRIMARY_KEY":return this.generateModifyPrimaryKeyCode(t);default:return {up:null,down:null}}}generateCreateTableCode(t){let e=t.data,r=[];r.push(`this.schema.createTable(${this.quote(e.table)}, (table) => {`);for(let n of e.columns){let s=this.generateColumnCode(e.table,n,true);r.push(` ${s}`);}r.push("});");let o=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:o}}generateAddColumnCode(t){let{table:e,column:r}=t.data,o=this.generateColumnCode(e,r,false),n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:n,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:o}=t.data,n=this.generateColumnCodeForModify(e,r,o),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(o.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],n=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:o,down:n}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(m=>m.columnName===u)?.databaseName||u),s=n.length===1?this.quote(n[0]):`[${n.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.createIndex(${this.quote(e.table)}, ${s}, { constraintName: ${this.quote(e.index)} });`],l=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`];return {up:a,down:l}}generateDropIndexCode(t){let e=t.data,r=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`],o=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:o}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:o,referencedColumn:n,constraintName:s}=this.resolveRelationDetails(e),a=e.relation.onDelete?.toLowerCase(),l=e.relation.onUpdate?.toLowerCase(),u=[];s&&u.push(`constraintName: ${this.quote(s)}`),a&&u.push(`onDelete: ${this.quote(a)}`),l&&u.push(`onUpdate: ${this.quote(l)}`);let d=u.length>0?`, { ${u.join(", ")} }`:"",m=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(o)}, ${this.quote(n)}${d});`,"});"],c=s||Z(e.table,r,o),p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(c)});`,"});"];return {up:m,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,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],n=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:o,down:n}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=`[${(e.columns||[]).map(u=>r?.getColumns().find(m=>m.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,o=t.constraint||e.name;if(!o||!r)return {up:null,down:null};if(e.type==="primary_key"){let a=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});"],l=[`// TODO: reverse primary key drop on ${this.quote(r)}`];return {up:a,down:l}}if(e.type==="unique"){let a=e.column,l=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],u=[`// TODO: reverse unique constraint drop for ${this.quote(a)} on ${this.quote(r)}`];return {up:l,down:u}}if(e.expression!==void 0){let a=[`this.schema.dropCheck(${this.quote(r)}, ${this.quote(o)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:a,down:l}}let n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:n,down:s}}generateAddCheckCode(t){let e=t.data,r=[`this.schema.addCheck(${this.quote(e.table)}, ${this.quote(e.expression)}, { constraintName: ${this.quote(e.name)} });`],o=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:o}}generateAddPrimaryKeyCode(t){let e=t.data,n=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||ge(e.table,e.columns[0]),s=`[${e.columns.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.addConstraint("primary_key", { columns: ${s}, constraintName: ${this.quote(n)} });`,"});"],l=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`," table.dropPrimaryKey();","});"];return {up:a,down:l}}generateDropTableCode(t){let e=t.table||t.data?.table,r=[`this.schema.dropTable(${this.quote(e)});`],o=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:o}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],n=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:o,down:n}}generateColumnCode(t,e,r){let o=this.generateColumnTypeCode(e);if(!r)return o;if(e.isPrimary){let n=e.primaryKeyConstraintName||ge(t,e.columnName);o+=`.primaryKey({ constraintName: ${this.quote(n)} })`;}return e.unsigned&&(o+=".unsigned()"),e.zerofill&&(o+=".zerofill()"),e.constraints?.default!==void 0&&(o+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o+";"}generateColumnCodeForModify(t,e,r){let o=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?o+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&(o+=".default(null)"),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o}generateColumnTypeCode(t){let e=t.databaseName;if(Array.isArray(t.type)){let s=t.type.map(a=>this.quote(a)).join(", ");return `table.enum(${this.quote(e)}, [${s}])`}let r=t.type;if(new Set(["uuid","ulid","boolean","year","json","jsonb","binary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]).has(r))return `table.${r}(${this.quote(e)})`;if(r==="timestamp"||r==="datetime"){let s=[];return t.withTimezone&&s.push("withTimezone: true"),t.precision!=null&&s.push(`precision: ${t.precision}`),s.length>0?`table.${r}(${this.quote(e)}, { ${s.join(", ")} })`:`table.${r}(${this.quote(e)})`}return r==="date"||r==="time"?t.precision!=null?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="increment"||r==="bigIncrement"?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:r==="decimal"||r==="numeric"?t.precision!=null?t.scale!=null?`table.${r}(${this.quote(e)}, ${t.precision}, ${t.scale})`:`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="float"||r==="double"||r==="real"?t.precision!=null&&t.precision!==10?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="longtext"||r==="mediumtext"||r==="tinytext"?`table.${r}(${this.quote(e)})`:new Set(["varchar","char","string","integer","tinyint","smallint","mediumint","bigint","biginteger","varbinary"]).has(r)?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:xr.BUILTIN_COLUMN_TYPES.has(r)?`table.${r}(${this.quote(e)})`:t.length!=null?`table.custom(${this.quote(e)}, ${this.quote(r)}, ${t.length})`:`table.custom(${this.quote(e)}, ${this.quote(r)})`}resolveRelationDetails(t){let e=t.table,r="id";if(t.relation.type==="belongsTo"){let l=t.relation.model();e=l.table;let u=l.primaryKey||"id";r=l.getColumns().find(c=>c.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=C(t.relation.manyToManyOptions.throughModel);let l=C(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let n=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=n.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=C(t.relation.manyToManyOptions.leftForeignKey);s=n.find(d=>d.columnName===l)?.databaseName||l;}else s=n.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName: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))}};xr.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 Rr=xr;function ny(i){return i.replace(/\s+/g," ").trim()}function sy(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ie(i,t){let e=ny(t.toLowerCase()),r=sy(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var We=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql._models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(y=>y?.type!==void 0&&y?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let b of n.indexes)o.indexes.map(q=>q.name).includes(b.name)||e.data.indexesToAdd.push({table:r.table,index:b.name});let y=r.getUniques?.()||[];for(let b of y)e.data.uniquesToAdd.push({table:r.table,name:b.name||"mandatory",columns:b.columns});let T=r.getChecks?.()||[];for(let b of T)e.data.checksToAdd.push({table:r.table,name:b.name,expression:b.expression});for(let b of n.relations){if(b.type!=="belongsTo")continue;let q=C(b.constraintName);o.foreignKeys.find(M=>M.name===q)||e.data.relationsToAdd.push({table:r.table,relation:b,onDelete:b.onDelete,onUpdate:b.onUpdate});}return}for(let y of n.columns)o.columns.some(b=>b.name===y.databaseName||b.name===y.columnName)||e.data.columnsToAdd.push({table:r.table,column:y});let s=r.getColumns();for(let y of o.columns)s.some(b=>b.databaseName===y.name||b.columnName===y.name)||e.data.columnsToDrop.push({table:r.table,column:y.name});for(let y of n.indexes)o.indexes.map(T=>T.name).includes(y.name)||e.data.indexesToAdd.push({table:r.table,index:y.name});let a=r.getUniques?.()||[];for(let y of a)o.indexes.some(b=>b.name===y.name&&b.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:y.name||"mandatory",columns:y.columns});let l=o.foreignKeys.map(y=>y.name);for(let y of o.indexes)y.isUnique||l.includes(y.name)||n.indexes.map(b=>b.name).includes(y.name)||e.data.indexesToDrop.push({table:r.table,index:y.name});for(let y of o.indexes){if(!y.isUnique||y.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(b=>b.name).includes(y.name)||e.data.uniquesToDrop.push({table:r.table,name:y.name});}let u=r.getChecks?.()||[];for(let y of u)o.checkConstraints.some(b=>b.name===y.name)||e.data.checksToAdd.push({table:r.table,name:y.name,expression:y.expression});let d=new Set(u.map(y=>y.name)),m=n.columns.filter(y=>Array.isArray(y.type)),c=new Set(m.map(y=>y.databaseName||y.columnName));for(let y of o.checkConstraints)if(!d.has(y.name)){let T=[...c].find(b=>{let q=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),R=new RegExp(`[\\["\\[]?${q}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i"),M=new RegExp(`[\\("\\[]?${q}[\\)"\\]]?(?:::text)?\\s*=\\s*ANY\\s*\\(`,"i");return R.test(y.expression)||M.test(y.expression)});if(T){let b=m.find(R=>(R.databaseName||R.columnName)===T),q=o.columns.find(R=>R.name===T);if(b&&q?.enumValues&&Array.isArray(b.type)){let R=[...b.type].sort(),M=[...q.enumValues].sort();if(!(R.length===M.length&&R.every((D,_)=>D===M[_]))){e.data.checksToDrop.push({table:r.table,name:y.name});let D=e.sql.getDbType(),_=D==="mssql"?"[":'"',v=D==="mssql"?"]":'"',L=b.type.map($=>`'${$.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:y.name,expression:`${_}${T}${v} IN (${L})`});}}}else e.data.checksToDrop.push({table:r.table,name:y.name});}for(let y of n.columns){let T=o.columns.find(R=>R.name===y.databaseName||R.name===y.columnName);if(!T)continue;let b=!e.areColumnsEqual(T,y,o.indexes),q=e.getDefaultChange({table:r.table,dbColumns:T,modelColumn:y});(b||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:T,modelColumn:y});}for(let y of n.relations){if(y.type!=="belongsTo"&&y.type!=="manyToMany")continue;if(y.type==="manyToMany"&&y.manyToManyOptions){let q=C(y.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:C(y.manyToManyOptions.leftForeignKey),foreignKey:y.manyToManyOptions.leftForeignKey,constraintName:y.constraintName?C(y.constraintName):Z(q,C(y.manyToManyOptions.leftForeignKey||tl(r.table)),r.table),onDelete:y.onDelete,onUpdate:y.onUpdate},onDelete:y.onDelete,onUpdate:y.onUpdate});continue}let T=C(y.constraintName);if(T&&o.foreignKeys.some(q=>q.name===T))continue;o.foreignKeys.find(q=>e.relationMatchesDbRelation(r,y,q))||e.data.relationsToAdd.push({table:r.table,relation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}let p=new Set(n.relations.filter(y=>y.type==="belongsTo").map(y=>{let T=C(y.foreignKey)||y.columnName,q=r.getColumns().find(R=>R.columnName===T)?.databaseName||T;return C(y.constraintName)||Z(r.table,q,y.model().table)}));for(let y of o.foreignKeys){if(y.name&&p.has(y.name))continue;n.relations.find(b=>b.type!=="belongsTo"&&b.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,b,y))||e.data.relationsToDrop.push({table:r.table,relation:y});}for(let y of n.relations){if(y.type!=="belongsTo"&&y.type!=="manyToMany")continue;let T=o.foreignKeys.find(b=>e.relationMatchesDbRelation(r,y,b));T&&!e.areRelationsEqual(T,y)&&e.data.relationsToModify.push({table:r.table,dbRelation:T,modelRelation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}let f=r.primaryKey;if(f&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[f]}),o.primaryKey&&!f&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),f&&o.primaryKey){let y=r.getColumns().find(T=>T.columnName===f);y&&!e.arePrimaryKeysEqual(o.primaryKey,y)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:f});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getCodeStatements(){let e=new xt(this.sql).generateOperations(this.data);return new Rr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new xt(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),o={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let n of r)o[n.phase].push(...n.sqlStatements);return o}areColumnsEqual(t,e,r=[]){let o=t.name===e.databaseName,n=this.sql.getDbType(),s=Ie(n,t.dataType),a=typeof e.type=="string"?Ie(n,e.type):void 0;if(a&&o&&(o=s===a),Array.isArray(e.type)&&(n==="mysql"||n==="mariadb")){let u=[...e.type].sort(),d=t.enumValues?[...t.enumValues].sort():null;d&&o&&(o=u.length===d.length&&u.every((m,c)=>m===d[c]));}e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let u=e.constraints.nullable,d=t.isNullable;o=o&&u===d;}if(n==="mysql"||n==="mariadb"){if(e.unsigned!==void 0||t.unsigned!==void 0){let u=e.unsigned??false,d=t.unsigned??false;o&&(o=u===d);}if(e.zerofill!==void 0||t.zerofill!==void 0){let u=e.zerofill??false,d=t.zerofill??false;o&&(o=u===d);}}return o}areRelationsEqual(t,e){let r=C(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",m=u.getColumns().find(f=>f.columnName===d),c=u.table,p=m?.databaseName||d;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=C(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===u;}let n=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&o&&(o=n===a),l&&o&&(o=s===l),o}relationMatchesDbRelation(t,e,r){let o,n=e;if(n&&n.model){if(typeof n.model=="function"&&n.model.table)o=n.model;else if(typeof n.model=="function")try{let y=n.model();y&&y.table&&(o=y);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.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=(n.type||"belongsTo")==="belongsTo"?C(n.foreignKey):n.columnName,m=l.find(y=>y.columnName===d);m&&(d=m.databaseName);let c=o.primaryKey||"id",f=o.getColumns().find(y=>y.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===f}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Ie(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Ie(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",u=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&u?false:"drop";if(s&&a){let d=String(t.dbColumns.defaultValue),m=String(t.modelColumn.constraints?.default),c=this.normalizeDefaultValue(e,r,d),p=this.normalizeDefaultValue(e,o||r,m);return c!==p?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=C(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find($=>$.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find($=>$.columnName===l),m=a.getColumns().find($=>$.columnName===u);if(!d||!m)continue;let c=C(o.manyToManyOptions.leftForeignKey)||l,p=C(o.manyToManyOptions.rightForeignKey)||u,f=await this.sql.getTableSchema(n);if(!f.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(d,c),this.clonePkAsColumn(m,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let y=this.clonePkAsColumn(d,c),T=this.clonePkAsColumn(m,p),b=f.columns.find($=>$.name===c),q=f.columns.find($=>$.name===p),R=b?this.areColumnsEqual(b,y,f.indexes):false,M=q?this.areColumnsEqual(q,T,f.indexes):false;for(let $ of f.foreignKeys){let V=$.referencedTable===s.table,ee=$.referencedTable===a.table;if(!V&&!ee)continue;let Oe=V?c:p,Ce=$.columns[0];Ce&&Ce!==Oe&&(this.data.relationsToDrop.push({table:n,relation:$}),Ce!==c&&Ce!==p&&this.data.columnsToDrop.push({table:n,column:Ce}));}let O={};R||(O[y.databaseName]=y),M||(O[T.databaseName]=O[T.databaseName]||T);for(let $ of Object.keys(O))this.data.columnsToAdd.push({table:n,column:O[$]});let D=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),_=this.buildBelongsToRelation(n,o.model,p,u,void 0,o.onDelete,o.onUpdate),v=f.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===c),L=f.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===p);if(!v){let $=f.foreignKeys.find(V=>V.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(D);}if(!L){let $=f.foreignKeys.find(V=>V.referencedTable===a.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(_);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,m=C(a.constraintName)||Z(o.table,d,a.model().table);s.add(m);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(y=>y.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let u=o.table,d=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let y=o.relation.model();u=y.table;let T=y.primaryKey||"id";d=y.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let m=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(y=>{if(y.columns.length!==1||y.referencedColumns.length!==1)return false;let T=m.has(y.columns[0]),b=y.referencedTable===u,q=y.referencedColumns[0]===d;return T&&b&&q}),p=C(o.relation.constraintName)||Z(o.table,l,u),f=e.get(o.table)||new Set;if(c||p&&f.has(p))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let y=C(o.relation.manyToManyOptions.throughModel),T=C(o.relation.manyToManyOptions.leftForeignKey),b=C(o.relation.manyToManyOptions.rightForeignKey),q=o.table===y&&o.relation.columnName===T&&o.relation.model().table===s?.table,R=o.table===y&&o.relation.columnName===b&&o.relation.model().table!==s?.table,M=await this.sql.getTableSchema(y),O=M.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===T&&_.referencedTable===(s?.table||"")),D=M.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===b&&_.referencedTable===o.relation.model().table);if(q&&O||R&&D)return null}return o})).then(o=>o.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async o=>{let n=this.models.find(u=>u.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let m=a.find(T=>T.columnName===u.foreignKey)?.databaseName||u.foreignKey,c=u.model(),p=c.primaryKey||"id",y=c.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===y})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?C(n):Z(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var ut=class extends S{constructor(e,r=false,o){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e,this.returning=o;}};var U=class extends S{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var z=class extends S{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var be=class extends S{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Me=class extends S{constructor(e,r=[],o=[],n=false,s){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o,this.returning=s;}};var A=class extends S{constructor(e,r,o=false,n,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=o,this.operator=n,this.value=s;}};var Se=class extends S{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var se=class extends A{constructor(e,r,o=false,n,s,a=false){super(e,r,o,"=",s,a);this.file="where_json";this.jsonOperator=n,this.value=s;}};var Te=class extends S{constructor(e,r,o,n="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=o,this.chainsWith=` ${n}`;}};var Dp;Dp=Symbol.toStringTag;var Y=class{constructor(t,e,r,o){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=o;this[Dp]="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 iy=async(i,t,e,r,o,n=false)=>{let s=Object.create(t.prototype),a=null;for(let l of Object.keys(i)){let u=i[l],d=r.get(l)?.columnName??l,m=e.has(d),c=n?true:o?o.has(d):true;if(m){if(!c)continue;if(u===null){s[d]=null;continue}let p=e.get(d);if(p?.serialize){let f=p.serialize(u);f!==null&&typeof f?.then=="function"?(a||(a=[]),a.push({key:d,promise:f})):s[d]=f;continue}s[d]=u;continue}(!n||o&&o.has(d))&&(s[d]=u);}if(a){let l=await Promise.all(a.map(u=>u.promise));for(let u=0;u<a.length;u++)s[a[u].key]=l[u];}if(o)for(let l of o)l in s||(s[l]=null);return s},_e=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),o=t.getColumnsByDatabaseName(),n=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let p=u.match(/\s+as\s+(.+)$/i);p&&s.push(p[1].trim());continue}let m=u;if(m.includes(".")&&(m=m.split(".").pop()),m==="*")continue;let c=r.get(m)?.columnName??m;s.push(c);}let a=s.length?new Set(s):null,l=await Promise.all(i.map(u=>iy(u,t,r,o,a,n)));return l.length===1?l[0]:l};var ay=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,ly=/^\d{4}-\d{2}-\d{2}$/,nl=i=>typeof i!="string"?i:ay.test(i)?new Date(i.replace(" ","T")+"Z"):ly.test(i)?new Date(i+"T00:00:00Z"):i,uy=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),Ip=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await uy(r):t[e]=r;}return t};var Or=class extends Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},Pp=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((u,d)=>{n.run(i,t,function(m){m&&d(m),u(this.changes);});});if(r.mode==="fetch")return new Promise((u,d)=>{n.all(i,t,(m,c)=>{m&&d(m),(!c||!c.length)&&u([]),u(c);});});let s=r?.typeofModel;if(!s)return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);let f=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m([f]);return}let y=f?.[a]||this.lastID;if(!y)return c(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[y],(b,q)=>{if(b)return c(b);m([q]);});});});if(!Array.isArray(r.models))throw new N("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let u=r.models;if(!a)return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);m(u);});});let d=[];return new Promise(async(m,c)=>{try{let p=u.map(async f=>{let y=new h(s),{columns:T,values:b}=await y.prepareColumns(Object.keys(f),Object.values(f),"insert"),q=Object.fromEntries(T.map((D,_)=>[D,b[_]])),R=new w(s,e.getDbType()),{sql:M,bindings:O}=R.parse([new z(new U(s.table),[q])]);return new Promise((D,_)=>{n.run(M,O,function(v){if(v)return _(v);let L=f[a]||this.lastID;if(!L)return _(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let $=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get($,[L],(V,ee)=>{if(V)return _(V);D(ee);});});})});d=await Promise.all(p),m(d);}catch(p){c(p);}})}return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});})};var Ot=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);}},Ep=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"};function At(i){let t=performance.now()-i;return Math.round(t*100)/100}var J=async(i,t,e,r,o="rows",n)=>{await e.ensureConnected();let s={sql:i,params:t,model:void 0,operation:Ep(i),timestamp:performance.now()};try{let l=e.observerChain;l&&typeof l.notifyBefore=="function"&&await l.notifyBefore(s);}catch{}n?.shouldNotLog||oe(i,e.logs,t,e.inputDetails.queryFormatOptions,r);let a=performance.now();switch(r){case "mysql":case "mariadb":let l=e.sqlConnection??e.getPool(),u=await $t(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let L=At(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:L,result:u};await $.notifyAfter(V);}}catch{}return o==="affectedRows"?u[0].affectedRows:o==="raw"?u:u[0];case "postgres":case "cockroachdb":let d=e.sqlConnection??e.getPool(),m=0,c=i.replace(/\?/g,()=>`$${++m}`),p=await $t(()=>d.query(c,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let L=At(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:L,result:p};await $.notifyAfter(V);}}catch{}return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let f=await $t(()=>Pp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs),y=At(a);try{let L=e.observerChain;if(L&&typeof L.notifyAfter=="function"){let $={...s,duration:y,result:f};await L.notifyAfter($);}}catch{}return o==="raw"?Array.isArray(f)?f:[f]:f;case "mssql":let T=e.getPool(),b=e.sqlConnection?e.sqlConnection.request():T.request();t.forEach((L,$)=>{b.input(`p${$}`,L);});let q=0,R=i.replace(/\?|@(\d+)/g,()=>`@p${q++}`),M=await $t(()=>b.query(R),e.inputDetails.connectionPolicies?.retry,e.logs),O=At(a);try{let L=e.observerChain;if(L&&typeof L.notifyAfter=="function"){let $={...s,duration:O,result:M};await L.notifyAfter($);}}catch{}return o==="affectedRows"?M.rowsAffected[0]:o==="raw"?M:M.recordset;case "oracledb":let D=4002,_=null,v=!!e.sqlConnection;try{_=e.sqlConnection?e.sqlConnection:await e.getConnection();let L=t.map(nl),$=0,V=i.replace(/\?/g,()=>`:${++$}`),ee=await $t(()=>_.execute(V,L,{outFormat:D,autoCommit:!v}),e.inputDetails.connectionPolicies?.retry,e.logs),Oe=At(a);try{let pt=e.observerChain;if(pt&&typeof pt.notifyAfter=="function"){let Lt={...s,duration:Oe,result:ee};await pt.notifyAfter(Lt);}}catch{}return o==="affectedRows"?ee.rowsAffected:o==="raw"?ee:await Promise.all(ee.rows?.map(async pt=>{let Lt=await Ip(pt),yl={};for(let hl in Lt)yl[hl.toLowerCase()]=Lt[hl];return yl})??[])}finally{_&&!v&&await _.close();}default:throw new N("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},$r=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),m=0,c=false,p=false,f=()=>{try{a.release();}catch{}};return d.on("data",y=>{if(o.onData){m++,Promise.resolve(o.onData(l,y)).then(()=>{m--,c&&m===0&&!p&&(f(),l.end());}).catch(T=>{p=true,f(),l.destroy(T);});return}l.write(y);}),d.on("end",()=>{c=true,m===0&&!p&&(f(),l.end());}),d.on("error",y=>{p=true,f(),l.destroy(y);}),l.on("close",()=>{f();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new K("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,m=i.replace(/\?/g,()=>`$${++d}`),c=new l.default(m,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(c),f=0,y=false,T=false,b=q=>{try{a.release(q);}catch{}};return p.on("data",q=>{if(o.onData){f++,Promise.resolve(o.onData(u,q)).then(()=>{f--,y&&f===0&&!T&&(b(),u.end());}).catch(R=>{T=true,b(R),u.destroy(R);});return}u.write(q);}),p.on("end",()=>{y=true,f===0&&!T&&(b(),u.end());}),p.on("error",q=>{T=true,b(q),u.destroy(q);}),u}case "sqlite":{let s=e.sqlConnection??e.getPool();return new Or(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((f,y)=>{l.input(`p${y}`,f);});let u=0,d=i.replace(/\?|@(\d+)/g,()=>`@p${u++}`),m=0,c=false,p=false;return l.on("row",f=>{if(!p){if(o.onData){m++,Promise.resolve(o.onData(a,f)).then(()=>{m--,c&&m===0&&!p&&a.end();}).catch(y=>{p=true,a.destroy(y);});return}a.write(f);}}),l.on("error",f=>{p=true,a.destroy(f);}),l.on("done",()=>{c=true,m===0&&!p&&a.end();}),l.query(d),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=4002,d=0,m=i.replace(/\?/g,()=>`:${++d}`),c=t.map(nl),p=a.queryStream(m,c,{outFormat:u}),f=0,y=false,T=false,b=async()=>{try{await a.close();}catch{}};return p.on("data",q=>{if(T)return;let R={};for(let M in q)R[M.toLowerCase()]=q[M];if(o.onData){f++,Promise.resolve(o.onData(l,R)).then(()=>{f--,y&&f===0&&!T&&(b(),l.end());}).catch(M=>{T=true,b(),l.destroy(M);});return}l.write(R);}),p.on("end",()=>{y=true,f===0&&!T&&(b(),l.end());}),p.on("error",q=>{T=true,b(),l.destroy(q);}),l}default:throw new N("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function $t(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,Cl(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var Pe=class{};Pe.modelCaseConvention="camel",Pe.databaseCaseConvention="snake";function qe(i){return String(i).padStart(2,"0")}function cy(i,t){let e=i.getFullYear(),r=qe(i.getMonth()+1),o=qe(i.getDate()),n=qe(i.getHours()),s=qe(i.getMinutes()),a=qe(i.getSeconds());switch(t){case "ISO":return `${e}-${r}-${o} ${n}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${o}`;case "TIME_ONLY":return `${n}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}function vp(i,t){let e=i.getUTCFullYear(),r=qe(i.getUTCMonth()+1),o=qe(i.getUTCDate()),n=qe(i.getUTCHours()),s=qe(i.getUTCMinutes()),a=qe(i.getUTCSeconds());switch(t){case "ISO":return `${e}-${r}-${o} ${n}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${o}`;case "TIME_ONLY":return `${n}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}var Re=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");return e==="LOCAL"?cy(i,t):vp(i,t)};var dt=(i=new Date)=>vp(i,"ISO");var kp=(i,t)=>{try{let e=xe.createHash("sha256").update(i).digest(),r=xe.randomBytes(16),o=xe.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");return n+=o.final("hex"),`${r.toString("hex")}:${n}`}catch(e){throw new N("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Bp=(i,t)=>{try{let e=xe.createHash("sha256").update(i).digest(),r=String(t).trim(),[o,n]=r.split(":");if(!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=o.toLowerCase(),a=n.toLowerCase(),l=xe.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 N("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Qp=(i,t)=>{try{let e=xe.randomBytes(32),r=xe.randomBytes(16),o=xe.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new N("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Kp=(i,t)=>{try{let e=String(t).trim(),[r,o,n]=e.split(":");if(!r||!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=privateDecrypt(i,Buffer.from(o,"hex")),a=xe.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(n,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new N("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var G=class{static defineMetadata(t,e,r,o){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let n=this.store.get(r);n||(n=new Map,this.store.set(r,n));let s=n.get(o);s||(s=new Map,n.set(o,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let o=e;for(;o;){let n=this.store.get(o);if(n){let s=n.get(r);if(s&&s.has(t))return s.get(t)}o=Object.getPrototypeOf(o);}}};G.store=new WeakMap;var al="0123456789ABCDEFGHJKMNPQRSTVWXYZ",il=al.length,yy=10,hy=16,gy=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%il;e=al.charAt(o)+e,i=(i-o)/il;}return e},by=i=>{let t=randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=al.charAt(o%il);}return e},Lp=()=>{let i=Math.floor(Date.now()/1e3),t=gy(i,yy),e=by(hy);return t+e};var Dr=class extends we{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var Ir=class extends we{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Pr=class extends we{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Er=class extends we{constructor(e,r,o){super(e,r);this.type="manyToMany";this.primaryModel=o.primaryModel,this.relatedModel=e.table,this.throughModel=o.throughModel,this.leftForeignKey=o.leftForeignKey,this.rightForeignKey=o.rightForeignKey;}};function x(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(G.getMetadata(at,e))throw new N("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");G.defineMetadata(at,r,e),G.defineMetadata(at,r,e.constructor);}let n=i.databaseName??H(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??ge(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}};s.validate=i.validate;let a=G.getMetadata(wr,e)||[];a.push(s),G.defineMetadata(wr,a,e);}}x.primary=wy;x.date=vy;x.datetime=ky;x.timestamp=By;x.time=Qy;x.boolean=Ey;x.json=Ky;x.uuid=My;x.ulid=_y;x.integer=Sy;x.bigInteger=Oy;x.float=Ny;x.decimal=Ay;x.increment=qy;x.bigIncrement=Cy;x.string=Ry;x.text=xy;x.binary=$y;x.enum=Dy;x.encryption={symmetric:Iy,asymmetric:Py};function wy(i={}){return x({...i,primaryKey:true})}function Ny(i={}){return x({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 Sy(i={}){return x({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function qy(i={}){return x({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function Cy(i={}){return x({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function My(i={}){return x({type:"uuid",...i,prepare:t=>t||xe.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function _y(i={}){return x({type:"ulid",...i,prepare:t=>t||Lp(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Ry(i={}){return x({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function xy(i={}){return x({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Oy(i={}){return x({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 Ay(i={}){return x({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function $y(i={}){return x({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Dy(i,t={}){return x({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Iy(i){return x({...i,prepare:t=>t&&kp(i.key,t),serialize:t=>t&&Bp(i.key,t)})}function Py(i){return x({...i,prepare:t=>t&&Qp(i.publicKey,t),serialize:t=>t&&Kp(i.privateKey,t)})}function Ey(i={}){return x({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function vy(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i,s=!!o,a=!!r,l=()=>new Date,u=()=>Re(new Date,"DATE_ONLY",e),d=t?typeof o=="function"?o:u:typeof o=="function"?o:l,m=t?typeof r=="function"?r:u:typeof r=="function"?r:l;return x({type:"date",...n,autoUpdate:a,prepare:t?f=>f?a?m():f:s?d():null:f=>f?a?m():f:s?d():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?Re(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",...n.openApi||{}}})}function ky(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:o=false,autoCreate:n=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!n,d=!!o,m=()=>new Date,c=()=>Re(new Date,"ISO",a),p=t?typeof n=="function"?n:c:typeof n=="function"?n:m,f=t?typeof o=="function"?o:c:typeof o=="function"?o:m;return x({type:"datetime",...s,withTimezone:l,autoUpdate:d,prepare:t?b=>b?d?f():b:u?p():null:b=>b?d?f():b:u?p():null,serialize:t?b=>{if(b!==void 0)return b===null?null:b instanceof Date?Re(b,"ISO",a):String(b)}:b=>{if(b!==void 0)return b===null?null:b instanceof Date?b:new Date(b)},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function By(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:o=false,autoCreate:n=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!n,d=!!o,m=()=>new Date,c=()=>Re(new Date,"TIMESTAMP",a),p=t?typeof n=="function"?n:c:typeof n=="function"?n:m,f=t?typeof o=="function"?o:c:typeof o=="function"?o:m;return x({type:"timestamp",...s,withTimezone:l,autoUpdate:d,prepare:t?b=>b?d?f():b:u?p():null:b=>b?d?f():b:u?p():null,serialize:t?b=>{if(b!==void 0)return b===null?null:b instanceof Date?Re(b,"TIMESTAMP",a):String(b)}:b=>{if(b!==void 0)return b===null?null:b instanceof Date?b:new Date(b)},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function Qy(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i,s=!!o,a=!!r,l=()=>new Date,u=()=>Re(new Date,"TIME_ONLY",e),d=t?typeof o=="function"?o:u:typeof o=="function"?o:l,m=t?typeof r=="function"?r:u:typeof r=="function"?r:l;return x({type:"time",...n,autoUpdate:a,prepare:t?f=>f?a?m():f:s?d():null:f=>f?a?m():f:s?d():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?Re(f,"TIME_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},openApi:{type:"string",format:"time",description:"HH:mm:ss",...n.openApi||{}}})}function Ky(i={}){return x({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function jp(i){try{return G.getMetadata(wr,i.prototype)||[]}catch{return []}}function Wp(i){return G.getMetadata(el,i.prototype)||[]}function Up(i){return (G.getMetadata(el,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=C(s),l=o();switch(r){case "belongsTo":return new Dr(l,n,a);case "hasOne":return new Pr(l,n,a);case "hasMany":return new Ir(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new N("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=o();return new Er(u,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:C(e.manyToManyOptions.throughModel),leftForeignKey:C(e.manyToManyOptions.leftForeignKey),rightForeignKey:C(e.manyToManyOptions.rightForeignKey)});default:throw new N("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Fp(i){return G.getMetadata(at,i)||G.getMetadata(at,i.prototype)}function Vp(i){return G.getMetadata(Mp,i.prototype)||[]}function Jp(i){return G.getMetadata(_p,i.prototype)||[]}function Hp(i){return G.getMetadata(Rp,i.prototype)||[]}var ue=class{};ue.columns=new WeakMap,ue.byName=new WeakMap,ue.byDatabaseName=new WeakMap;var Ue=class extends Pe{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 Fp(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=ue.columns.get(this);return t||(t=jp(this),ue.columns.set(this,t)),t}static getColumnsByName(){let t=ue.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),ue.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=ue.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),ue.byDatabaseName.set(this,t)),t}static getRelations(){return Wp(this)}static getIndexes(){return Vp(this)}static getUniques(){return Jp(this)}static getChecks(){return Hp(this)}static async validate(t){var s,a;let e=this.getColumns(),r={},o=this.primaryKey,n=o&&t?.[o]!==void 0?"update":"insert";for(let l of e){let u=l.validate;if(!u)continue;let d=t?t[l.columnName]:void 0,m=Array.isArray(u)?u:[u];for(let c of m)try{let p=await c(d,{model:this,column:l.columnName,operation:n,data:t});if(!(p&&p.valid)){let f=p&&p.message||"Validation failed";(r[s=l.columnName]||(r[s]=[])).push(f);}}catch{(r[a=l.columnName]||(r[a]=[])).push("Validation error");}}if(Object.keys(r).length>0)throw new ft(r);return {valid:true}}};Ue.softDeleteColumn="deletedAt",Ue.softDeleteValue=dt();var Dt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Up(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new N("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function vr(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function zp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var ct=i=>typeof i=="number"?i:parseFloat(i);var de=class extends S{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var Fe=class extends S{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var kr=class extends S{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var Br=class extends S{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Ee=class extends S{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var ie=class extends S{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var It=class extends S{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var Qr=class extends S{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var Kr=class extends S{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Pt=class extends S{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var jr=class jr{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=jr.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 It(e));}),this}groupByRaw(t){return this.groupByNodes.push(new It(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Pt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Pt(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 Qr(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new Kr(t),this}};jr.EMPTY_MAP=new Map;var Lr=jr;var Ve=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new A(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new A(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 A(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new A(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 A(t,"and",false,"in",e)),this):(this.whereNodes.push(new A("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new A(t,"or",false,"in",e)),this):(this.whereNodes.push(new A("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new A(t,"and",true,"in",e)),this):(this.whereNodes.push(new A("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new A(t,"or",true,"in",e)),this):(this.whereNodes.push(new A("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new A(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new A(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new A(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new A(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 A(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 A(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 A(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 A(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new A(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new A(t,"or",true,"=",e??[],true)),this}};var Wr=class extends Lr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ie(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ie(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ie(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ie(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ie(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ie(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var Ur=class extends Wr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=H(s,this.model.databaseCaseConvention);this.selectNodes.push(new de(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=H(o,this.model.databaseCaseConvention);this.selectNodes.push(new de(n));}),this}selectRaw(e){return this.selectNodes.push(new de(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":H(r,this.model.databaseCaseConvention);return this.selectNodes.push(new de(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new 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 kr,this}distinctOn(...e){return this.distinctOnNode=new Br(e),this}selectJson(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Ee(e,"",r,"raw",true)),this}};var Fr=class extends Ur{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof B&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof B||typeof o=="function")?this.andWhereSubQuery(e,r,o):this.andWhere(e,r,o)}andWhere(e,r,o){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof B&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"and",false,n,s)),this}orWhere(e,r,o){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof B&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new A(e,"and",false,n,new I(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new A(e,"or",false,n,new I(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"and",true,n,s)),this}andWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"and",true,n,s)),this}orWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof B&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"or",true,n,s)),this}whereBetween(e,r,o){return this.andWhereBetween(e,r,o)}andWhereBetween(e,r,o){return this.whereNodes.push(new A(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new A(e,"or",false,"between",[r,o])),this}whereNotBetween(e,r,o){return this.andWhereNotBetween(e,r,o)}andWhereNotBetween(e,r,o){return this.whereNodes.push(new A(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new A(e,"or",true,"between",[r,o])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new A(e,"and",false,"in",r)),this):(this.whereNodes.push(new A("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new A(e,"or",false,"in",r)),this):(this.whereNodes.push(new A("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 A(e,"and",true,"in",r)),this):(this.whereNodes.push(new A("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new A(e,"or",true,"in",r)),this):(this.whereNodes.push(new A("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new A(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new A(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new A(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new A(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new A(e,"and",false,o?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new A(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new A(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new A(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new A(e,"or",true,o?"~":"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 Te("","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 Te("","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 Te("","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 Te("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new A(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new A(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Fe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Fe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof B)return e;let r=new B(this.model,this.sqlDataSource),o=e(r);return o!=null&&"extractQueryNodes"in o?o:r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Te(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Te(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Vr=class extends Fr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"or",false,"raw",e)),this}};var B=class i extends Vr{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new w(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new h(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource),s=r(n),a=s!=null&&"extractQueryNodes"in s?s:n;return this.selectNodes.push(new de(a.extractQueryNodes(),o)),this}return this.selectNodes.push(new de(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>J(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new N("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await $r(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let[s,a]=await this.executePaginateQueries(()=>this.many(),()=>n.getCount()),l=s[s.length-1],u=l?l[r.discriminator]:null;return [{paginationMetadata:zp(e,a),data:s},{key:r.discriminator,value:u}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new _t("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new _t("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new Le(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Le(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Le(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Le(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:vr(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new N("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource),n=e(o),a=(n!=null&&"extractQueryNodes"in n?n:o).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new lt("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new lt("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new N("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new lt("materialized",e,s.extractQueryNodes())),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new z(this.fromNode,[o],r,n),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((p,f)=>[p,a[f]]));this.insertNode=new z(this.fromNode,[l],r,n);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),m=await this.getSqlDataSource("write"),c=await J(u,d,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new z(this.fromNode,o,r,n),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async m=>{let{columns:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert");return Object.fromEntries(c.map((f,y)=>[f,p[y]]))}));this.insertNode=new z(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await J(a,l,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return d})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new z(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new be(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(l.map((y,T)=>[y,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:m,bindings:c}=this.astParser.parse([new z(new U(this.model.table),[d],void 0,true),new be(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),f=await J(m,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(f)?f:[f]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new z(new U(this.model.table),s,void 0,true),this.onDuplicateNode=new be(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async c=>{let{columns:p,values:f}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),y=Object.fromEntries(p.map((T,b)=>[T,f[b]]));a.push(y);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:u}=this.astParser.parse([new z(new U(this.model.table),a,void 0,true),new be(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),m=await J(l,u,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=v=>this.interpreterUtils.formatStringColumn("mssql",v),d=[],m=e.map(v=>`select ${a.map($=>(d.push(v[$]),`@${d.length}`)).join(", ")}`),c=a.map(u).join(", "),p=m.join(" union all "),f=r.map(v=>`target.${u(v)} = source.${u(v)}`).join(" and "),y=o.filter(v=>!r.includes(v)).map(v=>`target.${u(v)} = source.${u(v)}`).join(", "),T=a.map(u).join(", "),b=a.map(v=>`source.${u(v)}`).join(", "),q=n.returning&&n.returning.length?n.returning.map(v=>`inserted.${u(v)}`).join(", "):a.map(v=>`inserted.${u(v)}`).join(", "),M=(n.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",O=`merge into ${l} as target using (${p}) as source (${c}) on ${f} ${M} when not matched then insert (${T}) values (${b}) output ${q};`,D=await this.getSqlDataSource("write"),_=await J(O,d,D,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(_)?_:[_]}update(e,r){let o=Object.keys(e),n=Object.values(e);this.updateNode=new Me(this.fromNode,o,n,false,r);let s=r&&r.length>0;return new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:a,values:l}=await this.interpreterUtils.prepareColumns(o,n,"update");this.updateNode=new Me(this.fromNode,a,l,false,r);let{sql:u,bindings:d}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),m=await this.getSqlDataSource("write");return J(u,d,m,this.dbType,s?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:s?"fetch":"affectedRows"}})})}truncate(){return this.truncateNode=new it(this.fromNode),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await J(e,r,o,this.dbType,"rows");})}delete(e){this.deleteNode=new ut(this.fromNode,false,e);let r=e&&e.length>0;return new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:o,bindings:n}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),s=await this.getSqlDataSource("write");return J(o,n,s,this.dbType,r?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=dt()}=e||{};return this.updateNode=new Me(this.fromNode,[r],[o]),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Me(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return J(a,l,u,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return ze(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),o=Ge(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new de("*")]);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=j(this.modelSelectedColumns),e.distinctNode=j(this.distinctNode),e.distinctOnNode=j(this.distinctOnNode),e.selectNodes=j(this.selectNodes),e.withQuery=j(this.withQuery),e.joinNodes=j(this.joinNodes),e.whereNodes=j(this.whereNodes),e.groupByNodes=j(this.groupByNodes),e.havingNodes=j(this.havingNodes),e.orderByNodes=j(this.orderByNodes),e.lockQueryNodes=j(this.lockQueryNodes),e.unionNodes=j(this.unionNodes),e.withNodes=j(this.withNodes),e.fromNode=j(this.fromNode),e.limitNode=j(this.limitNode),e.offsetNode=j(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new de("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};function Yp(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:Ly(i)}function Ly(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 Je=class i extends B{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Dt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[o,n]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(o,n.columnName);}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new N(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a));if(!o.length)return [];let n=await _e(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await $r(r,o,n,e,{onData:async(a,l)=>{let u=this.addAdditionalColumnsToModel(l),d=await _e([u],this.model,this.modelSelectedColumns);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),a.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new N(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}upsert(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return n.upsertMany(s,a,[l],{updateOnConflict:o.updateOnConflict??true,returning:o.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=r.length>0?Object.keys(r[0]):[];return n.upsertMany(e,s,r,{updateOnConflict:o.updateOnConflict??true,returning:o.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource;return new ve(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,o){return this.getModelManager(o?.trx).updateRecord(e,r,o)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let o=this.model.primaryKey;if(!o)throw new N(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,o){let{column:n=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[n]:s};return this.getModelManager(o?.trx).updateRecord(e,a,{returning:o?.returning})}async firstOrInsert(e,r,o){let n=this.getModelManager(o?.trx),s=await n.findOne({where:e,ignoreHooks:["afterFetch","beforeFetch"]});if(s)return s;let a={...e,...r};return n.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,o,n,s={}){if(Array.isArray(o)||(o=[o]),!o.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new N(`${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=o.map((p,f)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...n?n(p,f):{}}));class m extends Ue{static get table(){return a.throughModel}}m.databaseCaseConvention="preserve",m.modelCaseConvention="preserve",await new ve(m,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let o=r.returning,n=super.update(e,o);return new Y(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),n))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new Y(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=e.returning,o=super.delete(r);return new Y(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),o))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,u]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:vr(e,r,u),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof B)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,o){let n,s={strategy:"auto"};typeof r=="function"?(n=r,o&&(s=o)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,n?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereExists(d),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereExists(d),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereNotExists(d),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=j(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}async processRelationsWithStrategy(e){let r=e.length,o=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),n=async s=>{let a=Yp({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of o)await n(s);return}await Promise.all(o.map(n));}async loadRelationViaJoin(e,r){let o=e.relation,n=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,o,n).many({ignoreHooks:["beforeFetch","afterFetch"]});this.mapJoinedResultsToModels(a,r,o,n);}buildJoinQuery(e,r,o){let n=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)n.selectNodes.push(j(s));else for(let[s]of this.model.getColumnsByDatabaseName())n.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=j(s);this.qualifyWhereNodeColumns(a,this.model.table),n.whereNodes.push(a);}for(let s of this.groupByNodes)n.groupByNodes.push(j(s));for(let s of this.orderByNodes)n.orderByNodes.push(j(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(n.limitNode=j(this.limitNode)),this.offsetNode&&(n.offsetNode=j(this.offsetNode))),r.type){case "hasOne":case "hasMany":n.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":n.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;n.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),n.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(n,r,e,o);for(let s of e.whereNodes)n.whereNodes.push(j(s));for(let s of e.orderByNodes)n.orderByNodes.push(j(s));return n}selectRelationColumnsWithAlias(e,r,o,n){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=o.selectNodes.filter(c=>typeof c.column=="string"),m=d.some(c=>c.column==="*"||c.column.endsWith(".*"));if(d.length===0||m)for(let[c,p]of u)e.selectRaw(`${a.table}.${c} as ${s}${n}${p.columnName}`);else for(let c of d){let p=c.column,f=p.includes(".")?p.split(".").pop():p,y=u.get(f)||l.get(f),T=y?.databaseName??f,b=c.alias??y?.columnName??f;e.selectRaw(`${a.table}.${T} as ${s}${n}${b}`);}}mapJoinedResultsToModels(e,r,o,n){let{columnName:s,type:a}=o,l=o.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];u.has(m)||u.set(m,[]);let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.get(m).push(c));}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||[];});}else {let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];if(!u.has(m)){let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.set(m,c));}}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||null;});}}extractRelationDataFromRow(e,r,o){let n=`${r}${o}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(n)){let d=u.substring(n.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof A)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Te)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Se)for(let o of e.nodes)this.qualifyWhereNodeColumns(o,r);}serializeRelationData(e,r){for(let o of Object.keys(e)){let n=r.get(o);n?.serialize&&e[o]!==null&&e[o]!==void 0&&(e[o]=n.serialize(e[o]));}}async loadRelationViaBatch(e,r){let o=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,o);}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let f=n.get(String(p));c[e.columnName]=f||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let f=s.get(String(p));c[e.columnName]=f||null;});break;case "hasMany":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let p=c[e.foreignKey];if(!p)return;let f=String(p);a.has(f)||a.set(f,[]),a.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=a.get(String(p))||[];c[e.columnName]=f;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,m=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||H(d,this.model.modelCaseConvention);o.forEach(c=>{let p=c[m];if(p==null)return;let f=String(p);u.has(f)||u.set(f,[]),delete c[m],u.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=u.get(String(p))||[];c[e.columnName]=f;});break;default:throw new N(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=xe.randomBytes(6).toString("hex"),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(_=>_.isRawValue?_.column:`${this.interpreterUtils.formatStringColumn(this.dbType,_.column)} ${_.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(u,_=>_.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,n));s&&m.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&m.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(_=>Co(_,u,e.model.table));return m.select(...c).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new N(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let f=e.limitNode?.limit,y=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(_=>_.includes(".")?_:`${r.model.table}.${_}`):[`${r.model.table}.*`];if(!f&&!y)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let b=xe.randomBytes(6).toString("hex"),q=`${r.model.table}_cte_${b}`,R=e.orderByNodes.map(_=>{if(_.isRawValue)return _.column;let v=_.column.includes(".")?_.column:`${r.model.table}.${_.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,v)} ${_.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let M=`${xe.randomBytes(6).toString("hex")}_left_foreign_key`,O=e.with(q,_=>_.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,M]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${R}) as rn_${b}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));f&&O.whereRaw(`rn_${b} <= ${f+(y||0)}`),y&&O.whereRaw(`rn_${b} > ${y}`);let D=T.map(_=>Co(_,q,e.model.table));return O.select(...D).select([`${q}.${M}`,p.leftForeignKey]).table(q);default:throw new N(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new h(r.model),a=new h(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new N(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 m=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(m).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new N(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e){let r={};return Object.entries(e).forEach(([o,n])=>{if(this.modelColumnsDatabaseNames.get(o)){r[o]=n;return}r[o]=n;}),r}};function Gp(){return {}}var ve=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Gp(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new w(this.model,this.sqlType),this.interpreterUtils=new h(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new N(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new N(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(u=>[u,t[u]])),o=!e.returning||e.returning.length===0,n=new z(new U(this.model.table),[r],e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Ge(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return ze(u,d)};return new Y(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(q){throw q}e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:u,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),m={};u.forEach((q,R)=>{let M=d[R];m[q]=M,t[q]??(t[q]=M);});let c=!e.returning||e.returning.length===0,{sql:p,bindings:f}=this.astParser.parse([new z(new U(this.model.table),[m],e.returning,c)]),y=await J(p,f,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let T=y[0];return T?(await this.model.afterFetch?.([T]),await _e([T],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(u=>Object.fromEntries(Object.keys(u).map(d=>[d,u[d]]))),o=!e.returning||e.returning.length===0,n=new z(new U(this.model.table),r,e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Ge(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return ze(u,d)};return new Y(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let T=this.model.primaryKey,b=Object.keys(t[0]||{});if(T&&!b.includes(T))return this.handleOracleIdentityInsert(t,e)}let u=new Array(t.length);await Promise.all(t.map(async(T,b)=>{let{columns:q,values:R}=await this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert"),M={};q.forEach((O,D)=>{let _=R[D];M[O]=_,T[O]??(T[O]=_);}),u[b]=M;}));let d=!e.returning||e.returning.length===0,{sql:m,bindings:c}=this.astParser.parse([new z(new U(this.model.table),u,e.returning,d)]),p=await J(m,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let f=p;return f.length?(await this.model.afterFetch?.(f),await _e(f,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(p=>[p,c[p]]))),s=new z(new U(this.model.table),n,void 0,true),a=o.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0;new be(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",a);let u=()=>{let c=this.astParser.parse([s]);return {sql:c.sql,bindings:c.bindings}},d=()=>{let c=this.astParser.parse([s]);return {sql:Ge(this.sqlDataSource,c.sql),bindings:c.bindings}},m=()=>{let{sql:c,bindings:p}=d();return ze(c,p)};return new Y(u,d,m,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async O=>{let{columns:D,values:_}=await this.interpreterUtils.prepareColumns(Object.keys(O),Object.values(O),"insert"),v=Object.fromEntries(D.map((L,$)=>[L,_[$]]));c.push(v);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let p=!o.returning||o.returning.length===0,f=!p&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0,{sql:y,bindings:T}=this.astParser.parse([new z(new U(this.model.table),c,void 0,true),new be(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",f)]),b=await J(y,T,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(p)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(b.length<r.length&&!(o.updateOnConflict??true)){let _=t[0],v=r.map($=>$[_]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(_,v).many()}let O=b;return await this.model.afterFetch?.(O),await _e(O,this.model,o.returning)||[]}let q=t[0],R=r.map(O=>O[q]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(q,R).many()})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=D=>this.interpreterUtils.formatStringColumn("mssql",D),u=[],d=t.map(D=>`select ${s.map(v=>(u.push(D[v]),`@${u.length}`)).join(", ")}`),m=s.map(l).join(", "),c=d.join(" union all "),p=e.map(D=>`target.${l(D)} = source.${l(D)}`).join(" and "),f=r.filter(D=>!e.includes(D)).map(D=>`target.${l(D)} = source.${l(D)}`).join(", "),y=s.map(l).join(", "),T=s.map(D=>`source.${l(D)}`).join(", "),b=o.returning&&o.returning.length?o.returning.map(D=>`inserted.${l(D)}`).join(", "):s.map(D=>`inserted.${l(D)}`).join(", "),R=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",M=`merge into ${a} as target using (${c}) as source (${m}) on ${p} ${R} when not matched then insert (${y}) values (${T}) output ${b};`,O=await J(M,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});if(O.length===0&&!(o.updateOnConflict??true)){let D=e[0],_=n.map(L=>L[D]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(D,_).many()}return O}async updateRecord(t,e,r){let o=new Set(this.model.getColumns().map(f=>f.columnName)),n=Object.keys(e).filter(f=>o.has(f)),s=n.map(f=>e[f]),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(n,s,"update"),{primaryKey:u}=this.model;if(!u)throw new N(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let{sql:m,bindings:c}=this.astParser.parse([new Me(new U(this.model.table),a,l),new A(u,"and",false,"=",t)]);if(await J(m,c,this.sqlDataSource,this.sqlType,"affectedRows"),!r?.returning||r.returning.length===0)return;let p=await this.findOneByPrimaryKey(t,r.returning);if(!p)throw new N(this.model.name+"::updateRecord","ROW_NOT_FOUND");return p}async deleteRecord(t){if(!this.model.primaryKey)throw new N(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new A(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:o}=this.astParser.parse([new ut(new U(this.model.table)),e]);await J(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new Je(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await _e([a],this.model):null}return await _e(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,f)=>{let y=a[f];l[p]=y,n[p]??(n[p]=y);});let{sql:u,bindings:d}=this.astParser.parse([new z(new U(this.model.table),[l],e.returning)]);await J(u,d,this.sqlDataSource,this.sqlType,"rows");let m=this.query().select(...e.returning||["*"]);for(let[p,f]of Object.entries(l))f!=null&&p!==o&&m.where(p,"=",f);o&&m.orderBy(o,"desc");let c=await m.one({ignoreHooks:["beforeFetch"]});if(c){let p=c;o&&p[o]&&(n[o]=p[o]),r.push(c);}else r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of n)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;o?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;o?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Zp=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??dt()});var Et=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=xe.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await t(e);return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),oe("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;oe("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new N("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){g.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new N("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new N("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw g.error(e),new K("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new N("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var ul=Symbol.for("hysteria.orm.SqlDataSource"),Xp,ef,mt=class i extends(ef=Ct,Xp=ul,ef){constructor(e){super(e);this[Xp]=true;this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new er;this.migrationConfig={path:P.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};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:Nt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new i(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure,this.lazyLoad=e?.lazyLoad??false;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&ul in e&&e[ul]===true}getOnSlaveServerFailure(){return this.onSlaveServerFailure}addObserver(e){return this.observerChain||(this.observerChain=new Ot([])),this.observerChain.add(e),this}static async useConnection(e,r){let o=new i(e);await o.connect();try{await r(o),o.isConnected&&await o.disconnect();}catch(n){throw o.isConnected&&await o.disconnect(),n}}async connect(){if(this.isConnected)throw new N("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await He(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await He(e.sqlType,e.inputDetails),e.ownsPool=true;}));}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new N("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,o){if(typeof o=="string"&&o in r)return e.from(r[o])}})}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new N("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new N("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,u=[];a?(l=r,u=o):(l=void 0,u=r!==void 0?[r,...o]:o);let d=so(JSON.stringify(u)),m=d?`${e}:${d}`:e,c=await this.cacheAdapter.get(m);if(c!==void 0)return c;let p=await n(...u);return await this.cacheAdapter.set(m,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new N("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=so(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await He(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this;if(typeof e=="string"){let n=new B(Zp(e,r),o);return r?.alias&&n.table(e,r.alias),n}return new Je(e,o)}schema(){if(!this.isConnected&&!this.lazyLoad)throw new N("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Rt(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new Et(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new N("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new Et(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{let a=await e(s);return await s.commit({throwErrorOnInactiveTransaction:!1}),a}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected&&!this.lazyLoad)throw new N("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new ve(e,this.globalTransaction.sql):new ve(e,this)}getPool(){if(!this.sqlPool)throw this.lazyLoad?new N("SqlDataSource::getPool - call ensureConnected() or connect() first when using lazyLoad","CONNECTION_NOT_ESTABLISHED"):new N("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;switch(await this.ensureConnected(),this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new N("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){oe("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),oe("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new N("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async introspectSchema(){let e=this.getDbType(),r;e==="postgres"||e==="cockroachdb"?r=`
317
+ `)}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"}};Cr=new WeakSet,Ap=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 we=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var Mr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===n.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(u=>u.table===n.table);if(l){let u=l.getColumns().find(d=>d.databaseName===n.column);if(u){u.isPrimary&&a.push(`pk.${n.table}`);let d=l.getRelations();for(let m of d)m.columnName===u.columnName&&a.push(`fk.${n.table}.${m.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let u of l)s(u);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),u=t.relationsToDrop?.find(d=>d.table===a&&d.relation.name===l);u&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:u,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(u)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let u of l)u.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):u.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(u=>u.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var _r=class _r{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new Mr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,o=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),n=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...o].filter(l=>n.has(l)));return e.filter(l=>{let u=r(l);return u?!(s.has(u)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new le(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===o.table)?.getColumns().find(u=>u.columnName===o.columns[0])?.primaryKeyConstraintName||ge(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,u=>{let d=a||ge(o.table,o.columns[0]);u.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}for(let o of t.checksToDrop||[]){let n=new le(this.sql.getDbType());n.dropCheck(o.table,o.name);let s=n.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}for(let o of t.checksToAdd||[]){let n=new le(this.sql.getDbType());n.addCheck(o.table,o.expression,{constraintName:o.name});let s=n.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=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 n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,Z(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=C(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s;if(Array.isArray(r.type))s=e.enum(o[0],r.type);else if(typeof r.type=="string"&&_r.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...o);else if(typeof r.type=="string")s=e.custom(o[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||ge(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new le(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=C(t.relation.manyToManyOptions.throughModel),r=C(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let o=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,n=C(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),p=c.primaryKey,y=c.getColumns().find(T=>T.columnName===p);if(y)n=y.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=H(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let p=c.getColumns(),f=p.find(y=>y.columnName===n);if(f)n=f.databaseName;else {let y=c.primaryKey||"id",T=p.find(b=>b.columnName===y);if(T)n=T.databaseName;else {let b=c?.databaseCaseConvention||"preserve";n=H(n||y,b);}}}else {let p=c.primaryKey||"id",y=c.getColumns().find(T=>T.columnName===p);if(y)n=y.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=H(p,T);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(c=>c.columnName===l);if(u)l=u.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=H(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(p=>p.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=H(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,p=C(c),f=a.find(y=>y.columnName===p);if(f)l=f.databaseName;else {let y=s?.databaseCaseConvention||"preserve";l=H(p,y);}}let d=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,c=>{let p=o||Z(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:d,onUpdate:m});}).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," "))}))}};_r.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var xt=_r;var xr=class xr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],o=null,n={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==o&&(o=s.phase,e.length>0&&e.push(""),e.push(`// ${n[o]}`));let{up:a,down:l}=this.generateOperationCode(s);a&&e.push(...a),l&&r.push(...l);}return {up:e,down:r}}generateOperationCode(t){switch(t.type){case "CREATE_TABLE":return this.generateCreateTableCode(t);case "ADD_COLUMN":return this.generateAddColumnCode(t);case "MODIFY_COLUMN":return this.generateModifyColumnCode(t);case "DROP_COLUMN":return this.generateDropColumnCode(t);case "CREATE_INDEX":return this.generateCreateIndexCode(t);case "DROP_INDEX":return this.generateDropIndexCode(t);case "ADD_FOREIGN_KEY":return this.generateAddForeignKeyCode(t);case "DROP_FOREIGN_KEY":return this.generateDropForeignKeyCode(t);case "ADD_UNIQUE_CONSTRAINT":return this.generateAddUniqueCode(t);case "DROP_CONSTRAINT":return this.generateDropConstraintCode(t);case "ADD_CHECK_CONSTRAINT":return this.generateAddCheckCode(t);case "ADD_PRIMARY_KEY":return this.generateAddPrimaryKeyCode(t);case "DROP_TABLE":return this.generateDropTableCode(t);case "MODIFY_PRIMARY_KEY":return this.generateModifyPrimaryKeyCode(t);default:return {up:null,down:null}}}generateCreateTableCode(t){let e=t.data,r=[];r.push(`this.schema.createTable(${this.quote(e.table)}, (table) => {`);for(let n of e.columns){let s=this.generateColumnCode(e.table,n,true);r.push(` ${s}`);}r.push("});");let o=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:o}}generateAddColumnCode(t){let{table:e,column:r}=t.data,o=this.generateColumnCode(e,r,false),n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:n,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:o}=t.data,n=this.generateColumnCodeForModify(e,r,o),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(o.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],n=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:o,down:n}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(m=>m.columnName===u)?.databaseName||u),s=n.length===1?this.quote(n[0]):`[${n.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.createIndex(${this.quote(e.table)}, ${s}, { constraintName: ${this.quote(e.index)} });`],l=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`];return {up:a,down:l}}generateDropIndexCode(t){let e=t.data,r=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`],o=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:o}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:o,referencedColumn:n,constraintName:s}=this.resolveRelationDetails(e),a=e.relation.onDelete?.toLowerCase(),l=e.relation.onUpdate?.toLowerCase(),u=[];s&&u.push(`constraintName: ${this.quote(s)}`),a&&u.push(`onDelete: ${this.quote(a)}`),l&&u.push(`onUpdate: ${this.quote(l)}`);let d=u.length>0?`, { ${u.join(", ")} }`:"",m=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(o)}, ${this.quote(n)}${d});`,"});"],c=s||Z(e.table,r,o),p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(c)});`,"});"];return {up:m,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,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],n=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:o,down:n}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=`[${(e.columns||[]).map(u=>r?.getColumns().find(m=>m.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,o=t.constraint||e.name;if(!o||!r)return {up:null,down:null};if(e.type==="primary_key"){let a=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});"],l=[`// TODO: reverse primary key drop on ${this.quote(r)}`];return {up:a,down:l}}if(e.type==="unique"){let a=e.column,l=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],u=[`// TODO: reverse unique constraint drop for ${this.quote(a)} on ${this.quote(r)}`];return {up:l,down:u}}if(e.expression!==void 0){let a=[`this.schema.dropCheck(${this.quote(r)}, ${this.quote(o)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:a,down:l}}let n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:n,down:s}}generateAddCheckCode(t){let e=t.data,r=[`this.schema.addCheck(${this.quote(e.table)}, ${this.quote(e.expression)}, { constraintName: ${this.quote(e.name)} });`],o=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:o}}generateAddPrimaryKeyCode(t){let e=t.data,n=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||ge(e.table,e.columns[0]),s=`[${e.columns.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.addConstraint("primary_key", { columns: ${s}, constraintName: ${this.quote(n)} });`,"});"],l=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`," table.dropPrimaryKey();","});"];return {up:a,down:l}}generateDropTableCode(t){let e=t.table||t.data?.table,r=[`this.schema.dropTable(${this.quote(e)});`],o=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:o}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],n=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:o,down:n}}generateColumnCode(t,e,r){let o=this.generateColumnTypeCode(e);if(!r)return o;if(e.isPrimary){let n=e.primaryKeyConstraintName||ge(t,e.columnName);o+=`.primaryKey({ constraintName: ${this.quote(n)} })`;}return e.unsigned&&(o+=".unsigned()"),e.zerofill&&(o+=".zerofill()"),e.constraints?.default!==void 0&&(o+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o+";"}generateColumnCodeForModify(t,e,r){let o=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?o+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&(o+=".default(null)"),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o}generateColumnTypeCode(t){let e=t.databaseName;if(Array.isArray(t.type)){let s=t.type.map(a=>this.quote(a)).join(", ");return `table.enum(${this.quote(e)}, [${s}])`}let r=t.type;if(new Set(["uuid","ulid","boolean","year","json","jsonb","binary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]).has(r))return `table.${r}(${this.quote(e)})`;if(r==="timestamp"||r==="datetime"){let s=[];return t.withTimezone&&s.push("withTimezone: true"),t.precision!=null&&s.push(`precision: ${t.precision}`),s.length>0?`table.${r}(${this.quote(e)}, { ${s.join(", ")} })`:`table.${r}(${this.quote(e)})`}return r==="date"||r==="time"?t.precision!=null?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="increment"||r==="bigIncrement"?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:r==="decimal"||r==="numeric"?t.precision!=null?t.scale!=null?`table.${r}(${this.quote(e)}, ${t.precision}, ${t.scale})`:`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="float"||r==="double"||r==="real"?t.precision!=null&&t.precision!==10?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="longtext"||r==="mediumtext"||r==="tinytext"?`table.${r}(${this.quote(e)})`:new Set(["varchar","char","string","integer","tinyint","smallint","mediumint","bigint","biginteger","varbinary"]).has(r)?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:xr.BUILTIN_COLUMN_TYPES.has(r)?`table.${r}(${this.quote(e)})`:t.length!=null?`table.custom(${this.quote(e)}, ${this.quote(r)}, ${t.length})`:`table.custom(${this.quote(e)}, ${this.quote(r)})`}resolveRelationDetails(t){let e=t.table,r="id";if(t.relation.type==="belongsTo"){let l=t.relation.model();e=l.table;let u=l.primaryKey||"id";r=l.getColumns().find(c=>c.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=C(t.relation.manyToManyOptions.throughModel);let l=C(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let n=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=n.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=C(t.relation.manyToManyOptions.leftForeignKey);s=n.find(d=>d.columnName===l)?.databaseName||l;}else s=n.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName: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))}};xr.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 Rr=xr;function ny(i){return i.replace(/\s+/g," ").trim()}function sy(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ie(i,t){let e=ny(t.toLowerCase()),r=sy(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var We=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql._models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(y=>y?.type!==void 0&&y?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let b of n.indexes)o.indexes.map(q=>q.name).includes(b.name)||e.data.indexesToAdd.push({table:r.table,index:b.name});let y=r.getUniques?.()||[];for(let b of y)e.data.uniquesToAdd.push({table:r.table,name:b.name||"mandatory",columns:b.columns});let T=r.getChecks?.()||[];for(let b of T)e.data.checksToAdd.push({table:r.table,name:b.name,expression:b.expression});for(let b of n.relations){if(b.type!=="belongsTo")continue;let q=C(b.constraintName);o.foreignKeys.find(M=>M.name===q)||e.data.relationsToAdd.push({table:r.table,relation:b,onDelete:b.onDelete,onUpdate:b.onUpdate});}return}for(let y of n.columns)o.columns.some(b=>b.name===y.databaseName||b.name===y.columnName)||e.data.columnsToAdd.push({table:r.table,column:y});let s=r.getColumns();for(let y of o.columns)s.some(b=>b.databaseName===y.name||b.columnName===y.name)||e.data.columnsToDrop.push({table:r.table,column:y.name});for(let y of n.indexes)o.indexes.map(T=>T.name).includes(y.name)||e.data.indexesToAdd.push({table:r.table,index:y.name});let a=r.getUniques?.()||[];for(let y of a)o.indexes.some(b=>b.name===y.name&&b.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:y.name||"mandatory",columns:y.columns});let l=o.foreignKeys.map(y=>y.name);for(let y of o.indexes)y.isUnique||l.includes(y.name)||n.indexes.map(b=>b.name).includes(y.name)||e.data.indexesToDrop.push({table:r.table,index:y.name});for(let y of o.indexes){if(!y.isUnique||y.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(b=>b.name).includes(y.name)||e.data.uniquesToDrop.push({table:r.table,name:y.name});}let u=r.getChecks?.()||[];for(let y of u)o.checkConstraints.some(b=>b.name===y.name)||e.data.checksToAdd.push({table:r.table,name:y.name,expression:y.expression});let d=new Set(u.map(y=>y.name)),m=n.columns.filter(y=>Array.isArray(y.type)),c=new Set(m.map(y=>y.databaseName||y.columnName));for(let y of o.checkConstraints)if(!d.has(y.name)){let T=[...c].find(b=>{let q=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),R=new RegExp(`[\\["\\[]?${q}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i"),M=new RegExp(`[\\("\\[]?${q}[\\)"\\]]?(?:::text)?\\s*=\\s*ANY\\s*\\(`,"i");return R.test(y.expression)||M.test(y.expression)});if(T){let b=m.find(R=>(R.databaseName||R.columnName)===T),q=o.columns.find(R=>R.name===T);if(b&&q?.enumValues&&Array.isArray(b.type)){let R=[...b.type].sort(),M=[...q.enumValues].sort();if(!(R.length===M.length&&R.every((D,_)=>D===M[_]))){e.data.checksToDrop.push({table:r.table,name:y.name});let D=e.sql.getDbType(),_=D==="mssql"?"[":'"',v=D==="mssql"?"]":'"',L=b.type.map($=>`'${$.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:y.name,expression:`${_}${T}${v} IN (${L})`});}}}else e.data.checksToDrop.push({table:r.table,name:y.name});}for(let y of n.columns){let T=o.columns.find(R=>R.name===y.databaseName||R.name===y.columnName);if(!T)continue;let b=!e.areColumnsEqual(T,y,o.indexes),q=e.getDefaultChange({table:r.table,dbColumns:T,modelColumn:y});(b||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:T,modelColumn:y});}for(let y of n.relations){if(y.type!=="belongsTo"&&y.type!=="manyToMany")continue;if(y.type==="manyToMany"&&y.manyToManyOptions){let q=C(y.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:C(y.manyToManyOptions.leftForeignKey),foreignKey:y.manyToManyOptions.leftForeignKey,constraintName:y.constraintName?C(y.constraintName):Z(q,C(y.manyToManyOptions.leftForeignKey||tl(r.table)),r.table),onDelete:y.onDelete,onUpdate:y.onUpdate},onDelete:y.onDelete,onUpdate:y.onUpdate});continue}let T=C(y.constraintName);if(T&&o.foreignKeys.some(q=>q.name===T))continue;o.foreignKeys.find(q=>e.relationMatchesDbRelation(r,y,q))||e.data.relationsToAdd.push({table:r.table,relation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}let p=new Set(n.relations.filter(y=>y.type==="belongsTo").map(y=>{let T=C(y.foreignKey)||y.columnName,q=r.getColumns().find(R=>R.columnName===T)?.databaseName||T;return C(y.constraintName)||Z(r.table,q,y.model().table)}));for(let y of o.foreignKeys){if(y.name&&p.has(y.name))continue;n.relations.find(b=>b.type!=="belongsTo"&&b.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,b,y))||e.data.relationsToDrop.push({table:r.table,relation:y});}for(let y of n.relations){if(y.type!=="belongsTo"&&y.type!=="manyToMany")continue;let T=o.foreignKeys.find(b=>e.relationMatchesDbRelation(r,y,b));T&&!e.areRelationsEqual(T,y)&&e.data.relationsToModify.push({table:r.table,dbRelation:T,modelRelation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}let f=r.primaryKey;if(f&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[f]}),o.primaryKey&&!f&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),f&&o.primaryKey){let y=r.getColumns().find(T=>T.columnName===f);y&&!e.arePrimaryKeysEqual(o.primaryKey,y)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:f});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getCodeStatements(){let e=new xt(this.sql).generateOperations(this.data);return new Rr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new xt(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),o={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let n of r)o[n.phase].push(...n.sqlStatements);return o}areColumnsEqual(t,e,r=[]){let o=t.name===e.databaseName,n=this.sql.getDbType(),s=Ie(n,t.dataType),a=typeof e.type=="string"?Ie(n,e.type):void 0;if(a&&o&&(o=s===a),Array.isArray(e.type)&&(n==="mysql"||n==="mariadb")){let u=[...e.type].sort(),d=t.enumValues?[...t.enumValues].sort():null;d&&o&&(o=u.length===d.length&&u.every((m,c)=>m===d[c]));}e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let u=e.constraints.nullable,d=t.isNullable;o=o&&u===d;}if(n==="mysql"||n==="mariadb"){if(e.unsigned!==void 0||t.unsigned!==void 0){let u=e.unsigned??false,d=t.unsigned??false;o&&(o=u===d);}if(e.zerofill!==void 0||t.zerofill!==void 0){let u=e.zerofill??false,d=t.zerofill??false;o&&(o=u===d);}}return o}areRelationsEqual(t,e){let r=C(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",m=u.getColumns().find(f=>f.columnName===d),c=u.table,p=m?.databaseName||d;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=C(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===u;}let n=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&o&&(o=n===a),l&&o&&(o=s===l),o}relationMatchesDbRelation(t,e,r){let o,n=e;if(n&&n.model){if(typeof n.model=="function"&&n.model.table)o=n.model;else if(typeof n.model=="function")try{let y=n.model();y&&y.table&&(o=y);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.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=(n.type||"belongsTo")==="belongsTo"?C(n.foreignKey):n.columnName,m=l.find(y=>y.columnName===d);m&&(d=m.databaseName);let c=o.primaryKey||"id",f=o.getColumns().find(y=>y.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===f}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Ie(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Ie(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",u=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&u?false:"drop";if(s&&a){let d=String(t.dbColumns.defaultValue),m=String(t.modelColumn.constraints?.default),c=this.normalizeDefaultValue(e,r,d),p=this.normalizeDefaultValue(e,o||r,m);return c!==p?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=C(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find($=>$.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find($=>$.columnName===l),m=a.getColumns().find($=>$.columnName===u);if(!d||!m)continue;let c=C(o.manyToManyOptions.leftForeignKey)||l,p=C(o.manyToManyOptions.rightForeignKey)||u,f=await this.sql.getTableSchema(n);if(!f.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(d,c),this.clonePkAsColumn(m,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let y=this.clonePkAsColumn(d,c),T=this.clonePkAsColumn(m,p),b=f.columns.find($=>$.name===c),q=f.columns.find($=>$.name===p),R=b?this.areColumnsEqual(b,y,f.indexes):false,M=q?this.areColumnsEqual(q,T,f.indexes):false;for(let $ of f.foreignKeys){let V=$.referencedTable===s.table,ee=$.referencedTable===a.table;if(!V&&!ee)continue;let Oe=V?c:p,Ce=$.columns[0];Ce&&Ce!==Oe&&(this.data.relationsToDrop.push({table:n,relation:$}),Ce!==c&&Ce!==p&&this.data.columnsToDrop.push({table:n,column:Ce}));}let O={};R||(O[y.databaseName]=y),M||(O[T.databaseName]=O[T.databaseName]||T);for(let $ of Object.keys(O))this.data.columnsToAdd.push({table:n,column:O[$]});let D=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),_=this.buildBelongsToRelation(n,o.model,p,u,void 0,o.onDelete,o.onUpdate),v=f.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===c),L=f.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===p);if(!v){let $=f.foreignKeys.find(V=>V.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(D);}if(!L){let $=f.foreignKeys.find(V=>V.referencedTable===a.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(_);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,m=C(a.constraintName)||Z(o.table,d,a.model().table);s.add(m);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(y=>y.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let u=o.table,d=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let y=o.relation.model();u=y.table;let T=y.primaryKey||"id";d=y.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let m=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(y=>{if(y.columns.length!==1||y.referencedColumns.length!==1)return false;let T=m.has(y.columns[0]),b=y.referencedTable===u,q=y.referencedColumns[0]===d;return T&&b&&q}),p=C(o.relation.constraintName)||Z(o.table,l,u),f=e.get(o.table)||new Set;if(c||p&&f.has(p))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let y=C(o.relation.manyToManyOptions.throughModel),T=C(o.relation.manyToManyOptions.leftForeignKey),b=C(o.relation.manyToManyOptions.rightForeignKey),q=o.table===y&&o.relation.columnName===T&&o.relation.model().table===s?.table,R=o.table===y&&o.relation.columnName===b&&o.relation.model().table!==s?.table,M=await this.sql.getTableSchema(y),O=M.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===T&&_.referencedTable===(s?.table||"")),D=M.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===b&&_.referencedTable===o.relation.model().table);if(q&&O||R&&D)return null}return o})).then(o=>o.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async o=>{let n=this.models.find(u=>u.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let m=a.find(T=>T.columnName===u.foreignKey)?.databaseName||u.foreignKey,c=u.model(),p=c.primaryKey||"id",y=c.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===y})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?C(n):Z(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var ut=class extends S{constructor(e,r=false,o){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e,this.returning=o;}};var U=class extends S{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var z=class extends S{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var be=class extends S{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Me=class extends S{constructor(e,r=[],o=[],n=false,s){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o,this.returning=s;}};var A=class extends S{constructor(e,r,o=false,n,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=o,this.operator=n,this.value=s;}};var Se=class extends S{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var se=class extends A{constructor(e,r,o=false,n,s,a=false){super(e,r,o,"=",s,a);this.file="where_json";this.jsonOperator=n,this.value=s;}};var Te=class extends S{constructor(e,r,o,n="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=o,this.chainsWith=` ${n}`;}};var Dp;Dp=Symbol.toStringTag;var Y=class{constructor(t,e,r,o){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=o;this[Dp]="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 iy=async(i,t,e,r,o,n=false)=>{let s=Object.create(t.prototype),a=null;for(let l of Object.keys(i)){let u=i[l],d=r.get(l)?.columnName??l,m=e.has(d),c=n?true:o?o.has(d):true;if(m){if(!c)continue;if(u===null){s[d]=null;continue}let p=e.get(d);if(p?.serialize){let f=p.serialize(u);f!==null&&typeof f?.then=="function"?(a||(a=[]),a.push({key:d,promise:f})):s[d]=f;continue}s[d]=u;continue}(!n||o&&o.has(d))&&(s[d]=u);}if(a){let l=await Promise.all(a.map(u=>u.promise));for(let u=0;u<a.length;u++)s[a[u].key]=l[u];}if(o)for(let l of o)l in s||(s[l]=null);return s},_e=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),o=t.getColumnsByDatabaseName(),n=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let p=u.match(/\s+as\s+(.+)$/i);p&&s.push(p[1].trim());continue}let m=u;if(m.includes(".")&&(m=m.split(".").pop()),m==="*")continue;let c=r.get(m)?.columnName??m;s.push(c);}let a=s.length?new Set(s):null,l=await Promise.all(i.map(u=>iy(u,t,r,o,a,n)));return l.length===1?l[0]:l};var ay=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,ly=/^\d{4}-\d{2}-\d{2}$/,nl=i=>typeof i!="string"?i:ay.test(i)?new Date(i.replace(" ","T")+"Z"):ly.test(i)?new Date(i+"T00:00:00Z"):i,uy=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),Ip=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await uy(r):t[e]=r;}return t};var Or=class extends Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},Pp=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((u,d)=>{n.run(i,t,function(m){m&&d(m),u(this.changes);});});if(r.mode==="fetch")return new Promise((u,d)=>{n.all(i,t,(m,c)=>{m&&d(m),(!c||!c.length)&&u([]),u(c);});});let s=r?.typeofModel;if(!s)return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);let f=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m([f]);return}let y=f?.[a]||this.lastID;if(!y)return c(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[y],(b,q)=>{if(b)return c(b);m([q]);});});});if(!Array.isArray(r.models))throw new N("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let u=r.models;if(!a)return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);m(u);});});let d=[];return new Promise(async(m,c)=>{try{let p=u.map(async f=>{let y=new h(s),{columns:T,values:b}=await y.prepareColumns(Object.keys(f),Object.values(f),"insert"),q=Object.fromEntries(T.map((D,_)=>[D,b[_]])),R=new w(s,e.getDbType()),{sql:M,bindings:O}=R.parse([new z(new U(s.table),[q])]);return new Promise((D,_)=>{n.run(M,O,function(v){if(v)return _(v);let L=f[a]||this.lastID;if(!L)return _(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let $=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get($,[L],(V,ee)=>{if(V)return _(V);D(ee);});});})});d=await Promise.all(p),m(d);}catch(p){c(p);}})}return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});})};var Ot=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);}},Ep=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"};function At(i){let t=performance.now()-i;return Math.round(t*100)/100}var J=async(i,t,e,r,o="rows",n)=>{await e.ensureConnected();let s={id:randomUUID(),sql:i,params:t,model:void 0,operation:Ep(i),timestamp:performance.now()};try{let l=e.observerChain;l&&typeof l.notifyBefore=="function"&&await l.notifyBefore(s);}catch{}n?.shouldNotLog||oe(i,e.logs,t,e.inputDetails.queryFormatOptions,r);let a=performance.now();switch(r){case "mysql":case "mariadb":let l=e.sqlConnection??e.getPool(),u=await $t(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let L=At(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:L,result:u};await $.notifyAfter(V);}}catch{}return o==="affectedRows"?u[0].affectedRows:o==="raw"?u:u[0];case "postgres":case "cockroachdb":let d=e.sqlConnection??e.getPool(),m=0,c=i.replace(/\?/g,()=>`$${++m}`),p=await $t(()=>d.query(c,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let L=At(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:L,result:p};await $.notifyAfter(V);}}catch{}return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let f=await $t(()=>Pp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs),y=At(a);try{let L=e.observerChain;if(L&&typeof L.notifyAfter=="function"){let $={...s,duration:y,result:f};await L.notifyAfter($);}}catch{}return o==="raw"?Array.isArray(f)?f:[f]:f;case "mssql":let T=e.getPool(),b=e.sqlConnection?e.sqlConnection.request():T.request();t.forEach((L,$)=>{b.input(`p${$}`,L);});let q=0,R=i.replace(/\?|@(\d+)/g,()=>`@p${q++}`),M=await $t(()=>b.query(R),e.inputDetails.connectionPolicies?.retry,e.logs),O=At(a);try{let L=e.observerChain;if(L&&typeof L.notifyAfter=="function"){let $={...s,duration:O,result:M};await L.notifyAfter($);}}catch{}return o==="affectedRows"?M.rowsAffected[0]:o==="raw"?M:M.recordset;case "oracledb":let D=4002,_=null,v=!!e.sqlConnection;try{_=e.sqlConnection?e.sqlConnection:await e.getConnection();let L=t.map(nl),$=0,V=i.replace(/\?/g,()=>`:${++$}`),ee=await $t(()=>_.execute(V,L,{outFormat:D,autoCommit:!v}),e.inputDetails.connectionPolicies?.retry,e.logs),Oe=At(a);try{let pt=e.observerChain;if(pt&&typeof pt.notifyAfter=="function"){let Lt={...s,duration:Oe,result:ee};await pt.notifyAfter(Lt);}}catch{}return o==="affectedRows"?ee.rowsAffected:o==="raw"?ee:await Promise.all(ee.rows?.map(async pt=>{let Lt=await Ip(pt),yl={};for(let hl in Lt)yl[hl.toLowerCase()]=Lt[hl];return yl})??[])}finally{_&&!v&&await _.close();}default:throw new N("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},$r=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),m=0,c=false,p=false,f=()=>{try{a.release();}catch{}};return d.on("data",y=>{if(o.onData){m++,Promise.resolve(o.onData(l,y)).then(()=>{m--,c&&m===0&&!p&&(f(),l.end());}).catch(T=>{p=true,f(),l.destroy(T);});return}l.write(y);}),d.on("end",()=>{c=true,m===0&&!p&&(f(),l.end());}),d.on("error",y=>{p=true,f(),l.destroy(y);}),l.on("close",()=>{f();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new K("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,m=i.replace(/\?/g,()=>`$${++d}`),c=new l.default(m,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(c),f=0,y=false,T=false,b=q=>{try{a.release(q);}catch{}};return p.on("data",q=>{if(o.onData){f++,Promise.resolve(o.onData(u,q)).then(()=>{f--,y&&f===0&&!T&&(b(),u.end());}).catch(R=>{T=true,b(R),u.destroy(R);});return}u.write(q);}),p.on("end",()=>{y=true,f===0&&!T&&(b(),u.end());}),p.on("error",q=>{T=true,b(q),u.destroy(q);}),u}case "sqlite":{let s=e.sqlConnection??e.getPool();return new Or(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((f,y)=>{l.input(`p${y}`,f);});let u=0,d=i.replace(/\?|@(\d+)/g,()=>`@p${u++}`),m=0,c=false,p=false;return l.on("row",f=>{if(!p){if(o.onData){m++,Promise.resolve(o.onData(a,f)).then(()=>{m--,c&&m===0&&!p&&a.end();}).catch(y=>{p=true,a.destroy(y);});return}a.write(f);}}),l.on("error",f=>{p=true,a.destroy(f);}),l.on("done",()=>{c=true,m===0&&!p&&a.end();}),l.query(d),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=4002,d=0,m=i.replace(/\?/g,()=>`:${++d}`),c=t.map(nl),p=a.queryStream(m,c,{outFormat:u}),f=0,y=false,T=false,b=async()=>{try{await a.close();}catch{}};return p.on("data",q=>{if(T)return;let R={};for(let M in q)R[M.toLowerCase()]=q[M];if(o.onData){f++,Promise.resolve(o.onData(l,R)).then(()=>{f--,y&&f===0&&!T&&(b(),l.end());}).catch(M=>{T=true,b(),l.destroy(M);});return}l.write(R);}),p.on("end",()=>{y=true,f===0&&!T&&(b(),l.end());}),p.on("error",q=>{T=true,b(),l.destroy(q);}),l}default:throw new N("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function $t(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,Cl(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var Pe=class{};Pe.modelCaseConvention="camel",Pe.databaseCaseConvention="snake";function qe(i){return String(i).padStart(2,"0")}function my(i,t){let e=i.getFullYear(),r=qe(i.getMonth()+1),o=qe(i.getDate()),n=qe(i.getHours()),s=qe(i.getMinutes()),a=qe(i.getSeconds());switch(t){case "ISO":return `${e}-${r}-${o} ${n}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${o}`;case "TIME_ONLY":return `${n}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}function vp(i,t){let e=i.getUTCFullYear(),r=qe(i.getUTCMonth()+1),o=qe(i.getUTCDate()),n=qe(i.getUTCHours()),s=qe(i.getUTCMinutes()),a=qe(i.getUTCSeconds());switch(t){case "ISO":return `${e}-${r}-${o} ${n}:${s}:${a}`;case "DATE_ONLY":return `${e}-${r}-${o}`;case "TIME_ONLY":return `${n}:${s}:${a}`;case "TIMESTAMP":return Math.floor(i.getTime()/1e3).toString()}}var Re=(i,t="ISO",e="UTC")=>{if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("Invalid date provided");return e==="LOCAL"?my(i,t):vp(i,t)};var dt=(i=new Date)=>vp(i,"ISO");var kp=(i,t)=>{try{let e=xe.createHash("sha256").update(i).digest(),r=xe.randomBytes(16),o=xe.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");return n+=o.final("hex"),`${r.toString("hex")}:${n}`}catch(e){throw new N("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Bp=(i,t)=>{try{let e=xe.createHash("sha256").update(i).digest(),r=String(t).trim(),[o,n]=r.split(":");if(!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=o.toLowerCase(),a=n.toLowerCase(),l=xe.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 N("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Qp=(i,t)=>{try{let e=xe.randomBytes(32),r=xe.randomBytes(16),o=xe.createCipheriv("aes-256-cbc",e,r),n=o.update(t,"utf8","hex");n+=o.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${n}`}catch(e){throw new N("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Kp=(i,t)=>{try{let e=String(t).trim(),[r,o,n]=e.split(":");if(!r||!o||!n)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=privateDecrypt(i,Buffer.from(o,"hex")),a=xe.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(n,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new N("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var G=class{static defineMetadata(t,e,r,o){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let n=this.store.get(r);n||(n=new Map,this.store.set(r,n));let s=n.get(o);s||(s=new Map,n.set(o,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let o=e;for(;o;){let n=this.store.get(o);if(n){let s=n.get(r);if(s&&s.has(t))return s.get(t)}o=Object.getPrototypeOf(o);}}};G.store=new WeakMap;var al="0123456789ABCDEFGHJKMNPQRSTVWXYZ",il=al.length,hy=10,gy=16,by=(i,t)=>{let e="";for(let r=0;r<t;r++){let o=i%il;e=al.charAt(o)+e,i=(i-o)/il;}return e},Ty=i=>{let t=randomBytes(i),e="";for(let r=0;r<i;r++){let o=t[r];e+=al.charAt(o%il);}return e},Lp=()=>{let i=Math.floor(Date.now()/1e3),t=by(i,hy),e=Ty(gy);return t+e};var Dr=class extends we{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var Ir=class extends we{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var Pr=class extends we{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var Er=class extends we{constructor(e,r,o){super(e,r);this.type="manyToMany";this.primaryModel=o.primaryModel,this.relatedModel=e.table,this.throughModel=o.throughModel,this.leftForeignKey=o.leftForeignKey,this.rightForeignKey=o.rightForeignKey;}};function x(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(G.getMetadata(at,e))throw new N("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");G.defineMetadata(at,r,e),G.defineMetadata(at,r,e.constructor);}let n=i.databaseName??H(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??ge(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}};s.validate=i.validate;let a=G.getMetadata(wr,e)||[];a.push(s),G.defineMetadata(wr,a,e);}}x.primary=Ny;x.date=ky;x.datetime=By;x.timestamp=Qy;x.time=Ky;x.boolean=vy;x.json=Ly;x.uuid=_y;x.ulid=Ry;x.integer=qy;x.bigInteger=Ay;x.float=Sy;x.decimal=$y;x.increment=Cy;x.bigIncrement=My;x.string=xy;x.text=Oy;x.binary=Dy;x.enum=Iy;x.encryption={symmetric:Py,asymmetric:Ey};function Ny(i={}){return x({...i,primaryKey:true})}function Sy(i={}){return x({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 qy(i={}){return x({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function Cy(i={}){return x({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function My(i={}){return x({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function _y(i={}){return x({type:"uuid",...i,prepare:t=>t||xe.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function Ry(i={}){return x({type:"ulid",...i,prepare:t=>t||Lp(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function xy(i={}){return x({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Oy(i={}){return x({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Ay(i={}){return x({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 $y(i={}){return x({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function Dy(i={}){return x({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Iy(i,t={}){return x({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Py(i){return x({...i,prepare:t=>t&&kp(i.key,t),serialize:t=>t&&Bp(i.key,t)})}function Ey(i){return x({...i,prepare:t=>t&&Qp(i.publicKey,t),serialize:t=>t&&Kp(i.privateKey,t)})}function vy(i={}){return x({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function ky(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i,s=!!o,a=!!r,l=()=>new Date,u=()=>Re(new Date,"DATE_ONLY",e),d=t?typeof o=="function"?o:u:typeof o=="function"?o:l,m=t?typeof r=="function"?r:u:typeof r=="function"?r:l;return x({type:"date",...n,autoUpdate:a,prepare:t?f=>f?a?m():f:s?d():null:f=>f?a?m():f:s?d():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?Re(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",...n.openApi||{}}})}function By(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:o=false,autoCreate:n=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!n,d=!!o,m=()=>new Date,c=()=>Re(new Date,"ISO",a),p=t?typeof n=="function"?n:c:typeof n=="function"?n:m,f=t?typeof o=="function"?o:c:typeof o=="function"?o:m;return x({type:"datetime",...s,withTimezone:l,autoUpdate:d,prepare:t?b=>b?d?f():b:u?p():null:b=>b?d?f():b:u?p():null,serialize:t?b=>{if(b!==void 0)return b===null?null:b instanceof Date?Re(b,"ISO",a):String(b)}:b=>{if(b!==void 0)return b===null?null:b instanceof Date?b:new Date(b)},openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function Qy(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:o=false,autoCreate:n=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!n,d=!!o,m=()=>new Date,c=()=>Re(new Date,"TIMESTAMP",a),p=t?typeof n=="function"?n:c:typeof n=="function"?n:m,f=t?typeof o=="function"?o:c:typeof o=="function"?o:m;return x({type:"timestamp",...s,withTimezone:l,autoUpdate:d,prepare:t?b=>b?d?f():b:u?p():null:b=>b?d?f():b:u?p():null,serialize:t?b=>{if(b!==void 0)return b===null?null:b instanceof Date?Re(b,"TIMESTAMP",a):String(b)}:b=>{if(b!==void 0)return b===null?null:b instanceof Date?b:new Date(b)},openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function Ky(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i,s=!!o,a=!!r,l=()=>new Date,u=()=>Re(new Date,"TIME_ONLY",e),d=t?typeof o=="function"?o:u:typeof o=="function"?o:l,m=t?typeof r=="function"?r:u:typeof r=="function"?r:l;return x({type:"time",...n,autoUpdate:a,prepare:t?f=>f?a?m():f:s?d():null:f=>f?a?m():f:s?d():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?Re(f,"TIME_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},openApi:{type:"string",format:"time",description:"HH:mm:ss",...n.openApi||{}}})}function Ly(i={}){return x({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function jp(i){try{return G.getMetadata(wr,i.prototype)||[]}catch{return []}}function Wp(i){return G.getMetadata(el,i.prototype)||[]}function Up(i){return (G.getMetadata(el,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=C(s),l=o();switch(r){case "belongsTo":return new Dr(l,n,a);case "hasOne":return new Pr(l,n,a);case "hasMany":return new Ir(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new N("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=o();return new Er(u,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:C(e.manyToManyOptions.throughModel),leftForeignKey:C(e.manyToManyOptions.leftForeignKey),rightForeignKey:C(e.manyToManyOptions.rightForeignKey)});default:throw new N("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Fp(i){return G.getMetadata(at,i)||G.getMetadata(at,i.prototype)}function Vp(i){return G.getMetadata(Mp,i.prototype)||[]}function Jp(i){return G.getMetadata(_p,i.prototype)||[]}function Hp(i){return G.getMetadata(Rp,i.prototype)||[]}var ue=class{};ue.columns=new WeakMap,ue.byName=new WeakMap,ue.byDatabaseName=new WeakMap;var Ue=class extends Pe{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 Fp(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=ue.columns.get(this);return t||(t=jp(this),ue.columns.set(this,t)),t}static getColumnsByName(){let t=ue.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),ue.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=ue.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),ue.byDatabaseName.set(this,t)),t}static getRelations(){return Wp(this)}static getIndexes(){return Vp(this)}static getUniques(){return Jp(this)}static getChecks(){return Hp(this)}static async validate(t){var s,a;let e=this.getColumns(),r={},o=this.primaryKey,n=o&&t?.[o]!==void 0?"update":"insert";for(let l of e){let u=l.validate;if(!u)continue;let d=t?t[l.columnName]:void 0,m=Array.isArray(u)?u:[u];for(let c of m)try{let p=await c(d,{model:this,column:l.columnName,operation:n,data:t});if(!(p&&p.valid)){let f=p&&p.message||"Validation failed";(r[s=l.columnName]||(r[s]=[])).push(f);}}catch{(r[a=l.columnName]||(r[a]=[])).push("Validation error");}}if(Object.keys(r).length>0)throw new ft(r);return {valid:true}}};Ue.softDeleteColumn="deletedAt",Ue.softDeleteValue=dt();var Dt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Up(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new N("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function vr(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function zp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var ct=i=>typeof i=="number"?i:parseFloat(i);var de=class extends S{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var Fe=class extends S{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var kr=class extends S{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var Br=class extends S{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Ee=class extends S{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var ie=class extends S{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var It=class extends S{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var Qr=class extends S{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var Kr=class extends S{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Pt=class extends S{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var jr=class jr{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=jr.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 It(e));}),this}groupByRaw(t){return this.groupByNodes.push(new It(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Pt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Pt(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 Qr(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new Kr(t),this}};jr.EMPTY_MAP=new Map;var Lr=jr;var Ve=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new A(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new A(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new A(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 A(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new A(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 A(t,"and",false,"in",e)),this):(this.whereNodes.push(new A("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new A(t,"or",false,"in",e)),this):(this.whereNodes.push(new A("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new A(t,"and",true,"in",e)),this):(this.whereNodes.push(new A("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new A(t,"or",true,"in",e)),this):(this.whereNodes.push(new A("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new A(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new A(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new A(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new A(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 A(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 A(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 A(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 A(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new A(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new A(t,"or",true,"=",e??[],true)),this}};var Wr=class extends Lr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ie(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ie(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ie(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ie(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ie(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ie(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ve(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var Ur=class extends Wr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=H(s,this.model.databaseCaseConvention);this.selectNodes.push(new de(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=H(o,this.model.databaseCaseConvention);this.selectNodes.push(new de(n));}),this}selectRaw(e){return this.selectNodes.push(new de(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":H(r,this.model.databaseCaseConvention);return this.selectNodes.push(new de(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new 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 kr,this}distinctOn(...e){return this.distinctOnNode=new Br(e),this}selectJson(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Ee(e,"",r,"raw",true)),this}};var Fr=class extends Ur{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof B&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof B||typeof o=="function")?this.andWhereSubQuery(e,r,o):this.andWhere(e,r,o)}andWhere(e,r,o){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof B&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"and",false,n,s)),this}orWhere(e,r,o){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof B&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new A(e,"and",false,n,new I(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new A(e,"or",false,n,new I(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"and",true,n,s)),this}andWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"and",true,n,s)),this}orWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof B&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof B||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof B)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new A(e,"or",true,n,s)),this}whereBetween(e,r,o){return this.andWhereBetween(e,r,o)}andWhereBetween(e,r,o){return this.whereNodes.push(new A(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new A(e,"or",false,"between",[r,o])),this}whereNotBetween(e,r,o){return this.andWhereNotBetween(e,r,o)}andWhereNotBetween(e,r,o){return this.whereNodes.push(new A(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new A(e,"or",true,"between",[r,o])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new A(e,"and",false,"in",r)),this):(this.whereNodes.push(new A("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new A(e,"or",false,"in",r)),this):(this.whereNodes.push(new A("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 A(e,"and",true,"in",r)),this):(this.whereNodes.push(new A("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new A(e,"or",true,"in",r)),this):(this.whereNodes.push(new A("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new A(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new A(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new A(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new A(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new A(e,"and",false,o?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new A(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new A(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new A(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new A(e,"or",true,o?"~":"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 Te("","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 Te("","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 Te("","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 Te("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new A(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new A(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Fe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Fe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof B)return e;let r=new B(this.model,this.sqlDataSource),o=e(r);return o!=null&&"extractQueryNodes"in o?o:r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Te(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new Te(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Vr=class extends Fr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"or",false,"raw",e)),this}};var B=class i extends Vr{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new w(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new h(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource),s=r(n),a=s!=null&&"extractQueryNodes"in s?s:n;return this.selectNodes.push(new de(a.extractQueryNodes(),o)),this}return this.selectNodes.push(new de(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>J(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new N("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await $r(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let[s,a]=await this.executePaginateQueries(()=>this.many(),()=>n.getCount()),l=s[s.length-1],u=l?l[r.discriminator]:null;return [{paginationMetadata:zp(e,a),data:s},{key:r.discriminator,value:u}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new _t("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new _t("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new Le(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Le(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Le(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Le(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?ct(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:vr(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new N("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource),n=e(o),a=(n!=null&&"extractQueryNodes"in n?n:o).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new lt("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new lt("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new N("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new lt("materialized",e,s.extractQueryNodes())),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new z(this.fromNode,[o],r,n),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((p,f)=>[p,a[f]]));this.insertNode=new z(this.fromNode,[l],r,n);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),m=await this.getSqlDataSource("write"),c=await J(u,d,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new z(this.fromNode,o,r,n),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async m=>{let{columns:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert");return Object.fromEntries(c.map((f,y)=>[f,p[y]]))}));this.insertNode=new z(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await J(a,l,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return d})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new z(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new be(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(l.map((y,T)=>[y,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:m,bindings:c}=this.astParser.parse([new z(new U(this.model.table),[d],void 0,true),new be(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),f=await J(m,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(f)?f:[f]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new z(new U(this.model.table),s,void 0,true),this.onDuplicateNode=new be(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async c=>{let{columns:p,values:f}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),y=Object.fromEntries(p.map((T,b)=>[T,f[b]]));a.push(y);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:u}=this.astParser.parse([new z(new U(this.model.table),a,void 0,true),new be(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),m=await J(l,u,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=v=>this.interpreterUtils.formatStringColumn("mssql",v),d=[],m=e.map(v=>`select ${a.map($=>(d.push(v[$]),`@${d.length}`)).join(", ")}`),c=a.map(u).join(", "),p=m.join(" union all "),f=r.map(v=>`target.${u(v)} = source.${u(v)}`).join(" and "),y=o.filter(v=>!r.includes(v)).map(v=>`target.${u(v)} = source.${u(v)}`).join(", "),T=a.map(u).join(", "),b=a.map(v=>`source.${u(v)}`).join(", "),q=n.returning&&n.returning.length?n.returning.map(v=>`inserted.${u(v)}`).join(", "):a.map(v=>`inserted.${u(v)}`).join(", "),M=(n.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",O=`merge into ${l} as target using (${p}) as source (${c}) on ${f} ${M} when not matched then insert (${T}) values (${b}) output ${q};`,D=await this.getSqlDataSource("write"),_=await J(O,d,D,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(_)?_:[_]}update(e,r){let o=Object.keys(e),n=Object.values(e);this.updateNode=new Me(this.fromNode,o,n,false,r);let s=r&&r.length>0;return new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:a,values:l}=await this.interpreterUtils.prepareColumns(o,n,"update");this.updateNode=new Me(this.fromNode,a,l,false,r);let{sql:u,bindings:d}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),m=await this.getSqlDataSource("write");return J(u,d,m,this.dbType,s?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:s?"fetch":"affectedRows"}})})}truncate(){return this.truncateNode=new it(this.fromNode),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await J(e,r,o,this.dbType,"rows");})}delete(e){this.deleteNode=new ut(this.fromNode,false,e);let r=e&&e.length>0;return new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:o,bindings:n}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),s=await this.getSqlDataSource("write");return J(o,n,s,this.dbType,r?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=dt()}=e||{};return this.updateNode=new Me(this.fromNode,[r],[o]),new Y(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Me(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return J(a,l,u,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return ze(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),o=Ge(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new de("*")]);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=j(this.modelSelectedColumns),e.distinctNode=j(this.distinctNode),e.distinctOnNode=j(this.distinctOnNode),e.selectNodes=j(this.selectNodes),e.withQuery=j(this.withQuery),e.joinNodes=j(this.joinNodes),e.whereNodes=j(this.whereNodes),e.groupByNodes=j(this.groupByNodes),e.havingNodes=j(this.havingNodes),e.orderByNodes=j(this.orderByNodes),e.lockQueryNodes=j(this.lockQueryNodes),e.unionNodes=j(this.unionNodes),e.withNodes=j(this.withNodes),e.fromNode=j(this.fromNode),e.limitNode=j(this.limitNode),e.offsetNode=j(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new de("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};function Yp(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:jy(i)}function jy(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 Je=class i extends B{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Dt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[o,n]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(o,n.columnName);}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new N(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a));if(!o.length)return [];let n=await _e(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await $r(r,o,n,e,{onData:async(a,l)=>{let u=this.addAdditionalColumnsToModel(l),d=await _e([u],this.model,this.modelSelectedColumns);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),a.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new N(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}upsert(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return n.upsertMany(s,a,[l],{updateOnConflict:o.updateOnConflict??true,returning:o.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=r.length>0?Object.keys(r[0]):[];return n.upsertMany(e,s,r,{updateOnConflict:o.updateOnConflict??true,returning:o.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource;return new ve(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,o){return this.getModelManager(o?.trx).updateRecord(e,r,o)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let o=this.model.primaryKey;if(!o)throw new N(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,o){let{column:n=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[n]:s};return this.getModelManager(o?.trx).updateRecord(e,a,{returning:o?.returning})}async firstOrInsert(e,r,o){let n=this.getModelManager(o?.trx),s=await n.findOne({where:e,ignoreHooks:["afterFetch","beforeFetch"]});if(s)return s;let a={...e,...r};return n.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,o,n,s={}){if(Array.isArray(o)||(o=[o]),!o.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new N(`${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=o.map((p,f)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...n?n(p,f):{}}));class m extends Ue{static get table(){return a.throughModel}}m.databaseCaseConvention="preserve",m.modelCaseConvention="preserve",await new ve(m,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let o=r.returning,n=super.update(e,o);return new Y(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),n))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new Y(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=e.returning,o=super.delete(r);return new Y(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),o))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,u]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:vr(e,r,u),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof B)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,o){let n,s={strategy:"auto"};typeof r=="function"?(n=r,o&&(s=o)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,n?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereExists(d),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereExists(d),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereNotExists(d),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=j(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}async processRelationsWithStrategy(e){let r=e.length,o=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),n=async s=>{let a=Yp({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of o)await n(s);return}await Promise.all(o.map(n));}async loadRelationViaJoin(e,r){let o=e.relation,n=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,o,n).many({ignoreHooks:["beforeFetch","afterFetch"]});this.mapJoinedResultsToModels(a,r,o,n);}buildJoinQuery(e,r,o){let n=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)n.selectNodes.push(j(s));else for(let[s]of this.model.getColumnsByDatabaseName())n.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=j(s);this.qualifyWhereNodeColumns(a,this.model.table),n.whereNodes.push(a);}for(let s of this.groupByNodes)n.groupByNodes.push(j(s));for(let s of this.orderByNodes)n.orderByNodes.push(j(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(n.limitNode=j(this.limitNode)),this.offsetNode&&(n.offsetNode=j(this.offsetNode))),r.type){case "hasOne":case "hasMany":n.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":n.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;n.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),n.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(n,r,e,o);for(let s of e.whereNodes)n.whereNodes.push(j(s));for(let s of e.orderByNodes)n.orderByNodes.push(j(s));return n}selectRelationColumnsWithAlias(e,r,o,n){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=o.selectNodes.filter(c=>typeof c.column=="string"),m=d.some(c=>c.column==="*"||c.column.endsWith(".*"));if(d.length===0||m)for(let[c,p]of u)e.selectRaw(`${a.table}.${c} as ${s}${n}${p.columnName}`);else for(let c of d){let p=c.column,f=p.includes(".")?p.split(".").pop():p,y=u.get(f)||l.get(f),T=y?.databaseName??f,b=c.alias??y?.columnName??f;e.selectRaw(`${a.table}.${T} as ${s}${n}${b}`);}}mapJoinedResultsToModels(e,r,o,n){let{columnName:s,type:a}=o,l=o.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];u.has(m)||u.set(m,[]);let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.get(m).push(c));}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||[];});}else {let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];if(!u.has(m)){let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.set(m,c));}}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||null;});}}extractRelationDataFromRow(e,r,o){let n=`${r}${o}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(n)){let d=u.substring(n.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof A)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Te)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Se)for(let o of e.nodes)this.qualifyWhereNodeColumns(o,r);}serializeRelationData(e,r){for(let o of Object.keys(e)){let n=r.get(o);n?.serialize&&e[o]!==null&&e[o]!==void 0&&(e[o]=n.serialize(e[o]));}}async loadRelationViaBatch(e,r){let o=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,o);}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let f=n.get(String(p));c[e.columnName]=f||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let f=s.get(String(p));c[e.columnName]=f||null;});break;case "hasMany":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let p=c[e.foreignKey];if(!p)return;let f=String(p);a.has(f)||a.set(f,[]),a.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=a.get(String(p))||[];c[e.columnName]=f;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,m=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||H(d,this.model.modelCaseConvention);o.forEach(c=>{let p=c[m];if(p==null)return;let f=String(p);u.has(f)||u.set(f,[]),delete c[m],u.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=u.get(String(p))||[];c[e.columnName]=f;});break;default:throw new N(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=xe.randomBytes(6).toString("hex"),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(_=>_.isRawValue?_.column:`${this.interpreterUtils.formatStringColumn(this.dbType,_.column)} ${_.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(u,_=>_.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,n));s&&m.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&m.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(_=>Co(_,u,e.model.table));return m.select(...c).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new N(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let f=e.limitNode?.limit,y=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(_=>_.includes(".")?_:`${r.model.table}.${_}`):[`${r.model.table}.*`];if(!f&&!y)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let b=xe.randomBytes(6).toString("hex"),q=`${r.model.table}_cte_${b}`,R=e.orderByNodes.map(_=>{if(_.isRawValue)return _.column;let v=_.column.includes(".")?_.column:`${r.model.table}.${_.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,v)} ${_.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let M=`${xe.randomBytes(6).toString("hex")}_left_foreign_key`,O=e.with(q,_=>_.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,M]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${R}) as rn_${b}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));f&&O.whereRaw(`rn_${b} <= ${f+(y||0)}`),y&&O.whereRaw(`rn_${b} > ${y}`);let D=T.map(_=>Co(_,q,e.model.table));return O.select(...D).select([`${q}.${M}`,p.leftForeignKey]).table(q);default:throw new N(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new h(r.model),a=new h(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new N(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 m=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(m).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new N(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e){let r={};return Object.entries(e).forEach(([o,n])=>{if(this.modelColumnsDatabaseNames.get(o)){r[o]=n;return}r[o]=n;}),r}};function Gp(){return {}}var ve=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Gp(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new w(this.model,this.sqlType),this.interpreterUtils=new h(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new N(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new N(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(u=>[u,t[u]])),o=!e.returning||e.returning.length===0,n=new z(new U(this.model.table),[r],e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Ge(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return ze(u,d)};return new Y(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(q){throw q}e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:u,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),m={};u.forEach((q,R)=>{let M=d[R];m[q]=M,t[q]??(t[q]=M);});let c=!e.returning||e.returning.length===0,{sql:p,bindings:f}=this.astParser.parse([new z(new U(this.model.table),[m],e.returning,c)]),y=await J(p,f,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let T=y[0];return T?(await this.model.afterFetch?.([T]),await _e([T],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(u=>Object.fromEntries(Object.keys(u).map(d=>[d,u[d]]))),o=!e.returning||e.returning.length===0,n=new z(new U(this.model.table),r,e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Ge(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return ze(u,d)};return new Y(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let T=this.model.primaryKey,b=Object.keys(t[0]||{});if(T&&!b.includes(T))return this.handleOracleIdentityInsert(t,e)}let u=new Array(t.length);await Promise.all(t.map(async(T,b)=>{let{columns:q,values:R}=await this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert"),M={};q.forEach((O,D)=>{let _=R[D];M[O]=_,T[O]??(T[O]=_);}),u[b]=M;}));let d=!e.returning||e.returning.length===0,{sql:m,bindings:c}=this.astParser.parse([new z(new U(this.model.table),u,e.returning,d)]),p=await J(m,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let f=p;return f.length?(await this.model.afterFetch?.(f),await _e(f,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(p=>[p,c[p]]))),s=new z(new U(this.model.table),n,void 0,true),a=o.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0;new be(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",a);let u=()=>{let c=this.astParser.parse([s]);return {sql:c.sql,bindings:c.bindings}},d=()=>{let c=this.astParser.parse([s]);return {sql:Ge(this.sqlDataSource,c.sql),bindings:c.bindings}},m=()=>{let{sql:c,bindings:p}=d();return ze(c,p)};return new Y(u,d,m,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async O=>{let{columns:D,values:_}=await this.interpreterUtils.prepareColumns(Object.keys(O),Object.values(O),"insert"),v=Object.fromEntries(D.map((L,$)=>[L,_[$]]));c.push(v);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let p=!o.returning||o.returning.length===0,f=!p&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0,{sql:y,bindings:T}=this.astParser.parse([new z(new U(this.model.table),c,void 0,true),new be(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",f)]),b=await J(y,T,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(p)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(b.length<r.length&&!(o.updateOnConflict??true)){let _=t[0],v=r.map($=>$[_]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(_,v).many()}let O=b;return await this.model.afterFetch?.(O),await _e(O,this.model,o.returning)||[]}let q=t[0],R=r.map(O=>O[q]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(q,R).many()})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=D=>this.interpreterUtils.formatStringColumn("mssql",D),u=[],d=t.map(D=>`select ${s.map(v=>(u.push(D[v]),`@${u.length}`)).join(", ")}`),m=s.map(l).join(", "),c=d.join(" union all "),p=e.map(D=>`target.${l(D)} = source.${l(D)}`).join(" and "),f=r.filter(D=>!e.includes(D)).map(D=>`target.${l(D)} = source.${l(D)}`).join(", "),y=s.map(l).join(", "),T=s.map(D=>`source.${l(D)}`).join(", "),b=o.returning&&o.returning.length?o.returning.map(D=>`inserted.${l(D)}`).join(", "):s.map(D=>`inserted.${l(D)}`).join(", "),R=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",M=`merge into ${a} as target using (${c}) as source (${m}) on ${p} ${R} when not matched then insert (${y}) values (${T}) output ${b};`,O=await J(M,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});if(O.length===0&&!(o.updateOnConflict??true)){let D=e[0],_=n.map(L=>L[D]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(D,_).many()}return O}async updateRecord(t,e,r){let o=new Set(this.model.getColumns().map(f=>f.columnName)),n=Object.keys(e).filter(f=>o.has(f)),s=n.map(f=>e[f]),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(n,s,"update"),{primaryKey:u}=this.model;if(!u)throw new N(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let{sql:m,bindings:c}=this.astParser.parse([new Me(new U(this.model.table),a,l),new A(u,"and",false,"=",t)]);if(await J(m,c,this.sqlDataSource,this.sqlType,"affectedRows"),!r?.returning||r.returning.length===0)return;let p=await this.findOneByPrimaryKey(t,r.returning);if(!p)throw new N(this.model.name+"::updateRecord","ROW_NOT_FOUND");return p}async deleteRecord(t){if(!this.model.primaryKey)throw new N(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new A(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:o}=this.astParser.parse([new ut(new U(this.model.table)),e]);await J(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new Je(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await _e([a],this.model):null}return await _e(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,f)=>{let y=a[f];l[p]=y,n[p]??(n[p]=y);});let{sql:u,bindings:d}=this.astParser.parse([new z(new U(this.model.table),[l],e.returning)]);await J(u,d,this.sqlDataSource,this.sqlType,"rows");let m=this.query().select(...e.returning||["*"]);for(let[p,f]of Object.entries(l))f!=null&&p!==o&&m.where(p,"=",f);o&&m.orderBy(o,"desc");let c=await m.one({ignoreHooks:["beforeFetch"]});if(c){let p=c;o&&p[o]&&(n[o]=p[o]),r.push(c);}else r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of n)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;o?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;o?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Zp=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??dt()});var Et=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=xe.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await t(e);return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),oe("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;oe("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":oe("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;oe("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":oe("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new N("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){g.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new N("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new N("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw g.error(e),new K("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new N("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var ul=Symbol.for("hysteria.orm.SqlDataSource"),Xp,ef,mt=class i extends(ef=Ct,Xp=ul,ef){constructor(e){super(e);this[Xp]=true;this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new er;this.migrationConfig={path:P.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};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:Nt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new i(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure,this.lazyLoad=e?.lazyLoad??false;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&ul in e&&e[ul]===true}getOnSlaveServerFailure(){return this.onSlaveServerFailure}addObserver(e){return this.observerChain||(this.observerChain=new Ot([])),this.observerChain.add(e),this}static async useConnection(e,r){let o=new i(e);await o.connect();try{await r(o),o.isConnected&&await o.disconnect();}catch(n){throw o.isConnected&&await o.disconnect(),n}}async connect(){if(this.isConnected)throw new N("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await He(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await He(e.sqlType,e.inputDetails),e.ownsPool=true;}));}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new N("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,o){if(typeof o=="string"&&o in r)return e.from(r[o])}})}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new N("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new N("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,u=[];a?(l=r,u=o):(l=void 0,u=r!==void 0?[r,...o]:o);let d=so(JSON.stringify(u)),m=d?`${e}:${d}`:e,c=await this.cacheAdapter.get(m);if(c!==void 0)return c;let p=await n(...u);return await this.cacheAdapter.set(m,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new N("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=so(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await He(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this;if(typeof e=="string"){let n=new B(Zp(e,r),o);return r?.alias&&n.table(e,r.alias),n}return new Je(e,o)}schema(){if(!this.isConnected&&!this.lazyLoad)throw new N("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Rt(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new Et(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new N("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new Et(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{let a=await e(s);return await s.commit({throwErrorOnInactiveTransaction:!1}),a}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected&&!this.lazyLoad)throw new N("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new ve(e,this.globalTransaction.sql):new ve(e,this)}getPool(){if(!this.sqlPool)throw this.lazyLoad?new N("SqlDataSource::getPool - call ensureConnected() or connect() first when using lazyLoad","CONNECTION_NOT_ESTABLISHED"):new N("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;switch(await this.ensureConnected(),this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new N("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){oe("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),oe("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new N("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async introspectSchema(){let e=this.getDbType(),r;e==="postgres"||e==="cockroachdb"?r=`
318
318
  SELECT table_schema AS schema_name, table_name
319
319
  FROM information_schema.tables
320
320
  WHERE table_type = 'BASE TABLE'
@@ -434,10 +434,10 @@ export default class extends BaseSeeder {
434
434
  console.log('Seeder completed');
435
435
  }
436
436
  }
437
- `}};var Fy=(i,t,e)=>{let r=e||"database/seeders",o=t?".js":".ts",s=`${Date.now()}_${i}${o}`;ne.existsSync(r)||(ne.mkdirSync(r,{recursive:true}),g.info(`Created seeders directory: ${r}`));let a=tt.join(r,s),l=zr.seederTemplate();ne.writeFileSync(a,l),g.info(`Seeder created successfully: ${a}`);},tf=Fy;var Vy=async(i,t,e)=>{let r=[];for(let o of t){let n=tt.resolve(process.cwd(),o);ne.existsSync(n)||(g.error(`Path not found: ${n}`),process.exit(1));let s=ne.statSync(n);if(s.isDirectory()){let a=ne.readdirSync(n).filter(l=>l.endsWith(".ts")||l.endsWith(".js")).sort();for(let l of a)r.push({file:l,folder:n});}else if(s.isFile()){let a=tt.basename(n),l=tt.dirname(n);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:o,folder:n}of r)try{g.info(`Running seeder: ${o}`);let s=tt.resolve(n,o),a=await et(s,e);if(!a.default){g.error(`Seeder ${o} does not export a default class`);continue}let l=new a.default(i);if(typeof l.run!="function"){g.error(`Seeder ${o} must have a run() method. Make sure it extends BaseSeeder from hysteria-orm`);continue}await l.run(),g.info(`\u2713 Completed seeder: ${o}`);}catch(s){throw g.error(`Failed to run seeder ${o}: ${s}`),s}g.info("All seeders completed successfully");},rf=Vy;function Q(i){return {_phantom:void 0,_apply:i}}function of(i){return Q((t,e)=>{x.date(i??{},false)(t,e);})}of.string=function(t){return Q((e,r)=>{x.date(t??{},true)(e,r);})};function nf(i){return Q((t,e)=>{x.datetime(i??{},false)(t,e);})}nf.string=function(t){return Q((e,r)=>{x.datetime(t??{},true)(e,r);})};function sf(i){return Q((t,e)=>{x.timestamp(i??{},false)(t,e);})}sf.string=function(t){return Q((e,r)=>{x.timestamp(t??{},true)(e,r);})};function af(i){return Q((t,e)=>{x.time(i??{},false)(t,e);})}af.string=function(t){return Q((e,r)=>{x.time(t??{},true)(e,r);})};var lf=Symbol("mongoProperties");function pl(){return (i,t)=>{let e=G.getMetadata(lf,i)||[];e.push(t),G.defineMetadata(lf,e,i);}}var Bt=class extends Pe{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}};bl([pl()],Bt.prototype,"id");function Hy(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 zy=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 uf(i,t){let e=Hy(i);switch(t){case "pascal":return co(e);case "camel":return rr(e);case "snake":return tr(e);default:return e}}function df(i){return zy.has(i)?{name:`${i}_`,wasSanitized:true}:{name:i,wasSanitized:false}}function cf(i,t){switch(t){case "snake":return `${tr(i)}.ts`;case "camel":return `${i}.ts`;default:return `${i}.ts`}}function mf(i,t){let{dataType:e,isNullable:r,defaultValue:o,length:n,precision:s,scale:a,withTimezone:l,unsigned:u}=t,d={};if(r||(d.nullable=false),o!=null){let p=String(o);!p.includes("(")&&!p.includes("CURRENT_")&&(d.default=o);}n!=null&&(d.length=n),s!=null&&(d.precision=s),a!=null&&(d.scale=a),u&&(d.unsigned=true);let m=e.toLowerCase();m.includes("timestamp")&&l&&(d.withTimezone=true);let c="string";return m.includes("varchar")||m.includes("char")?c="string":m.includes("text")?c="text":m==="integer"||m==="int"||m==="int4"?c="integer":m==="bigint"||m==="int8"?c="bigInteger":m==="smallint"||m==="int2"?c="smallint":m==="boolean"||m==="bool"?c="boolean":m.includes("timestamp")?c="timestamp":m==="date"?c="date":m==="time"?c="time":m==="uuid"?c="uuid":m==="json"?c="json":m==="jsonb"?c="jsonb":m==="decimal"||m==="numeric"?c="decimal":m==="float"||m==="real"||m==="double"||m==="double precision"?c="float":m==="binary"||m==="bytea"?c="binary":m==="enum"&&(c="enum",t.enumValues&&(d.enumValues=t.enumValues)),i==="mysql"&&m.includes("tinyint")&&n===1&&(c="boolean"),{method:c,options:d}}function ke(i){return JSON.stringify(i)}function pf(i){return i==null?"null":typeof i=="string"?ke(i):typeof i=="boolean"?i?"true":"false":typeof i=="number"?String(i):Array.isArray(i)?`[${i.map(pf).join(", ")}]`:String(i)}function ff(i,t,e,r){let o=[],n=new Set(t.primaryKey?.columns||[]),s=new Map;for(let u of t.foreignKeys)for(let d=0;d<u.columns.length;d++){let m=u.columns[d],c=u.referencedColumns[d];s.has(m)||s.set(m,{referencedTable:u.referencedTable,referencedColumns:[c],onDelete:u.onDelete,onUpdate:u.onUpdate});}o.push('import { col, defineModel } from "hysteria-orm";'),o.push(""),o.push(`export const ${i} = defineModel(${ke(i)}, {`),o.push(" columns: {");for(let u of t.columns){let m=df(u.name).name,c=n.has(u.name),{method:p,options:f}=mf(e,u),y=[];for(let[R,M]of Object.entries(f))M!=null&&y.push(`${R}: ${pf(M)}`);let T=y.length>0?`{ ${y.join(", ")} }`:"",b=T?`col.${p}(${T})`:`col.${p}()`,q=s.get(u.name);if(q){let R=q.referencedColumns.join(", "),M=`/** @fk references ${q.referencedTable}(${R})`;q.onDelete&&(M+=` \u2014 onDelete: ${q.onDelete}`),q.onUpdate&&(M+=` \u2014 onUpdate: ${q.onUpdate}`),M+=" */",o.push(` ${M}`);}c&&(o.push(" // Primary key column"),(p==="integer"||p==="bigInteger")&&o.push(" // TODO: may be auto-increment, verify manually")),o.push(` ${m}: ${b},`);}o.push(" },");let a=t.indexes.filter(u=>!u.isUnique);if(a.length>0){o.push(" indexes: [");for(let u of a)u.name?o.push(` { columns: [${u.columns.map(ke).join(", ")}], name: ${ke(u.name)} },`):o.push(` [${u.columns.map(ke).join(", ")}],`);o.push(" ],");}let l=t.indexes.filter(u=>u.isUnique);if(l.length>0){o.push(" uniques: [");for(let u of l)u.name?o.push(` { columns: [${u.columns.map(ke).join(", ")}], name: ${ke(u.name)} },`):o.push(` [${u.columns.map(ke).join(", ")}],`);o.push(" ],");}return o.push("});"),o.push(""),o.push(`export type ${i}Type = InstanceType<typeof ${i}>;`),o.push(""),o.join(`
437
+ `}};var Vy=(i,t,e)=>{let r=e||"database/seeders",o=t?".js":".ts",s=`${Date.now()}_${i}${o}`;ne.existsSync(r)||(ne.mkdirSync(r,{recursive:true}),g.info(`Created seeders directory: ${r}`));let a=tt.join(r,s),l=zr.seederTemplate();ne.writeFileSync(a,l),g.info(`Seeder created successfully: ${a}`);},tf=Vy;var Jy=async(i,t,e)=>{let r=[];for(let o of t){let n=tt.resolve(process.cwd(),o);ne.existsSync(n)||(g.error(`Path not found: ${n}`),process.exit(1));let s=ne.statSync(n);if(s.isDirectory()){let a=ne.readdirSync(n).filter(l=>l.endsWith(".ts")||l.endsWith(".js")).sort();for(let l of a)r.push({file:l,folder:n});}else if(s.isFile()){let a=tt.basename(n),l=tt.dirname(n);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:o,folder:n}of r)try{g.info(`Running seeder: ${o}`);let s=tt.resolve(n,o),a=await et(s,e);if(!a.default){g.error(`Seeder ${o} does not export a default class`);continue}let l=new a.default(i);if(typeof l.run!="function"){g.error(`Seeder ${o} must have a run() method. Make sure it extends BaseSeeder from hysteria-orm`);continue}await l.run(),g.info(`\u2713 Completed seeder: ${o}`);}catch(s){throw g.error(`Failed to run seeder ${o}: ${s}`),s}g.info("All seeders completed successfully");},rf=Jy;function Q(i){return {_phantom:void 0,_apply:i}}function of(i){return Q((t,e)=>{x.date(i??{},false)(t,e);})}of.string=function(t){return Q((e,r)=>{x.date(t??{},true)(e,r);})};function nf(i){return Q((t,e)=>{x.datetime(i??{},false)(t,e);})}nf.string=function(t){return Q((e,r)=>{x.datetime(t??{},true)(e,r);})};function sf(i){return Q((t,e)=>{x.timestamp(i??{},false)(t,e);})}sf.string=function(t){return Q((e,r)=>{x.timestamp(t??{},true)(e,r);})};function af(i){return Q((t,e)=>{x.time(i??{},false)(t,e);})}af.string=function(t){return Q((e,r)=>{x.time(t??{},true)(e,r);})};var lf=Symbol("mongoProperties");function pl(){return (i,t)=>{let e=G.getMetadata(lf,i)||[];e.push(t),G.defineMetadata(lf,e,i);}}var Bt=class extends Pe{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}};bl([pl()],Bt.prototype,"id");function zy(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 Yy=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 uf(i,t){let e=zy(i);switch(t){case "pascal":return co(e);case "camel":return rr(e);case "snake":return tr(e);default:return e}}function df(i){return Yy.has(i)?{name:`${i}_`,wasSanitized:true}:{name:i,wasSanitized:false}}function cf(i,t){switch(t){case "snake":return `${tr(i)}.ts`;case "camel":return `${i}.ts`;default:return `${i}.ts`}}function mf(i,t){let{dataType:e,isNullable:r,defaultValue:o,length:n,precision:s,scale:a,withTimezone:l,unsigned:u}=t,d={};if(r||(d.nullable=false),o!=null){let p=String(o);!p.includes("(")&&!p.includes("CURRENT_")&&(d.default=o);}n!=null&&(d.length=n),s!=null&&(d.precision=s),a!=null&&(d.scale=a),u&&(d.unsigned=true);let m=e.toLowerCase();m.includes("timestamp")&&l&&(d.withTimezone=true);let c="string";return m.includes("varchar")||m.includes("char")?c="string":m.includes("text")?c="text":m==="integer"||m==="int"||m==="int4"?c="integer":m==="bigint"||m==="int8"?c="bigInteger":m==="smallint"||m==="int2"?c="smallint":m==="boolean"||m==="bool"?c="boolean":m.includes("timestamp")?c="timestamp":m==="date"?c="date":m==="time"?c="time":m==="uuid"?c="uuid":m==="json"?c="json":m==="jsonb"?c="jsonb":m==="decimal"||m==="numeric"?c="decimal":m==="float"||m==="real"||m==="double"||m==="double precision"?c="float":m==="binary"||m==="bytea"?c="binary":m==="enum"&&(c="enum",t.enumValues&&(d.enumValues=t.enumValues)),i==="mysql"&&m.includes("tinyint")&&n===1&&(c="boolean"),{method:c,options:d}}function ke(i){return JSON.stringify(i)}function pf(i){return i==null?"null":typeof i=="string"?ke(i):typeof i=="boolean"?i?"true":"false":typeof i=="number"?String(i):Array.isArray(i)?`[${i.map(pf).join(", ")}]`:String(i)}function ff(i,t,e,r){let o=[],n=new Set(t.primaryKey?.columns||[]),s=new Map;for(let u of t.foreignKeys)for(let d=0;d<u.columns.length;d++){let m=u.columns[d],c=u.referencedColumns[d];s.has(m)||s.set(m,{referencedTable:u.referencedTable,referencedColumns:[c],onDelete:u.onDelete,onUpdate:u.onUpdate});}o.push('import { col, defineModel } from "hysteria-orm";'),o.push(""),o.push(`export const ${i} = defineModel(${ke(i)}, {`),o.push(" columns: {");for(let u of t.columns){let m=df(u.name).name,c=n.has(u.name),{method:p,options:f}=mf(e,u),y=[];for(let[R,M]of Object.entries(f))M!=null&&y.push(`${R}: ${pf(M)}`);let T=y.length>0?`{ ${y.join(", ")} }`:"",b=T?`col.${p}(${T})`:`col.${p}()`,q=s.get(u.name);if(q){let R=q.referencedColumns.join(", "),M=`/** @fk references ${q.referencedTable}(${R})`;q.onDelete&&(M+=` \u2014 onDelete: ${q.onDelete}`),q.onUpdate&&(M+=` \u2014 onUpdate: ${q.onUpdate}`),M+=" */",o.push(` ${M}`);}c&&(o.push(" // Primary key column"),(p==="integer"||p==="bigInteger")&&o.push(" // TODO: may be auto-increment, verify manually")),o.push(` ${m}: ${b},`);}o.push(" },");let a=t.indexes.filter(u=>!u.isUnique);if(a.length>0){o.push(" indexes: [");for(let u of a)u.name?o.push(` { columns: [${u.columns.map(ke).join(", ")}], name: ${ke(u.name)} },`):o.push(` [${u.columns.map(ke).join(", ")}],`);o.push(" ],");}let l=t.indexes.filter(u=>u.isUnique);if(l.length>0){o.push(" uniques: [");for(let u of l)u.name?o.push(` { columns: [${u.columns.map(ke).join(", ")}], name: ${ke(u.name)} },`):o.push(` [${u.columns.map(ke).join(", ")}],`);o.push(" ],");}return o.push("});"),o.push(""),o.push(`export type ${i}Type = InstanceType<typeof ${i}>;`),o.push(""),o.join(`
438
438
  `)}function yf(i){let t=[];for(let e of i)t.push(`export * from "./${e}";`);return t.push(""),t.join(`
439
- `)}var Yy=["pg_","information_schema","mysql","sys","performance_schema","sqlite_"];function Gy(i){let t=i.toLowerCase();return Yy.some(e=>t.startsWith(e))}async function fl(i,t){let{outDir:e,naming:r,dry:o}=t;g.info("Starting database introspection");let n=i.getDbType();g.info(`Database dialect: ${n}`);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 m of d.tables)Gy(m.name)||a.push(m.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 m=await i.getTableSchema(d);if(m.columns.length===0){g.warn(`Table ${d} has no columns, skipping`);continue}let c=uf(d,r),p=cf(c,r),f=ff(d,m,n,{naming:r});l.push(c),o?(g.info(`[DRY RUN] Would generate: ${p}`),g.info("---"),g.info(f),g.info("---")):u.push({fileName:p,content:f});}catch(m){g.error(`Failed to process table ${d}: ${m}`);}}if(!o){ne.existsSync(e)||(ne.mkdirSync(e,{recursive:true}),g.info(`Created output directory: ${e}`));for(let{fileName:d,content:m}of u){let c=tt.join(e,d);ne.writeFileSync(c,m,"utf-8"),g.info(`Generated: ${c}`);}if(l.length>0){let d=yf(l),m=tt.join(e,"index.ts");ne.writeFileSync(m,d,"utf-8"),g.info(`Generated: ${m}`);}}g.info(`
440
- Summary:`),g.info(` Tables processed: ${l.length}`),o?g.info(" Mode: Dry run (no files written)"):(g.info(` Output directory: ${e}`),g.info(` Files generated: ${u.length+1}`));}var gf={devDependencies:{"@types/ioredis":"^5.0.0","@types/mongodb":"^4.0.7","@types/mssql":"^9.1.11","@types/oracledb":"^6.10.2","@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",oracledb:"^6.10.0",pg:"^8.20.0",sqlite3:"^6.0.1",typescript:"^6.0.2"}};var Tf=()=>ne.existsSync(tt.join(process.cwd(),"yarn.lock"))?["yarn","add"]:ne.existsSync(tt.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add"]:ne.existsSync(tt.join(process.cwd(),"package-lock.json"))?["npm","install"]:ne.existsSync(tt.join(process.cwd(),"bun.lockb"))?["bun","add"]:ne.existsSync(tt.join(process.cwd(),"deno.lock"))?["deno","add"]:["npm","install"],bf=async(i,t,e,r)=>{let o=eh.createInterface({input:process.stdin,output:process.stdout}),n=e.join(", "),s=`Do you want to install the following dependencies using ${t}?
439
+ `)}var Gy=["pg_","information_schema","mysql","sys","performance_schema","sqlite_"];function Zy(i){let t=i.toLowerCase();return Gy.some(e=>t.startsWith(e))}async function fl(i,t){let{outDir:e,naming:r,dry:o}=t;g.info("Starting database introspection");let n=i.getDbType();g.info(`Database dialect: ${n}`);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 m of d.tables)Zy(m.name)||a.push(m.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 m=await i.getTableSchema(d);if(m.columns.length===0){g.warn(`Table ${d} has no columns, skipping`);continue}let c=uf(d,r),p=cf(c,r),f=ff(d,m,n,{naming:r});l.push(c),o?(g.info(`[DRY RUN] Would generate: ${p}`),g.info("---"),g.info(f),g.info("---")):u.push({fileName:p,content:f});}catch(m){g.error(`Failed to process table ${d}: ${m}`);}}if(!o){ne.existsSync(e)||(ne.mkdirSync(e,{recursive:true}),g.info(`Created output directory: ${e}`));for(let{fileName:d,content:m}of u){let c=tt.join(e,d);ne.writeFileSync(c,m,"utf-8"),g.info(`Generated: ${c}`);}if(l.length>0){let d=yf(l),m=tt.join(e,"index.ts");ne.writeFileSync(m,d,"utf-8"),g.info(`Generated: ${m}`);}}g.info(`
440
+ Summary:`),g.info(` Tables processed: ${l.length}`),o?g.info(" Mode: Dry run (no files written)"):(g.info(` Output directory: ${e}`),g.info(` Files generated: ${u.length+1}`));}var gf={devDependencies:{"@types/ioredis":"^5.0.0","@types/mongodb":"^4.0.7","@types/mssql":"^9.1.11","@types/oracledb":"^6.10.2","@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",oracledb:"^6.10.0",pg:"^8.20.0",sqlite3:"^6.0.1",typescript:"^6.0.2"}};var Tf=()=>ne.existsSync(tt.join(process.cwd(),"yarn.lock"))?["yarn","add"]:ne.existsSync(tt.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add"]:ne.existsSync(tt.join(process.cwd(),"package-lock.json"))?["npm","install"]:ne.existsSync(tt.join(process.cwd(),"bun.lockb"))?["bun","add"]:ne.existsSync(tt.join(process.cwd(),"deno.lock"))?["deno","add"]:["npm","install"],bf=async(i,t,e,r)=>{let o=th.createInterface({input:process.stdin,output:process.stdout}),n=e.join(", "),s=`Do you want to install the following dependencies using ${t}?
441
441
  ${n}
442
442
  (y/n): `;return new Promise(a=>{o.question(s,l=>{if(o.close(),l.toLowerCase()==="y"||l.toLowerCase()==="yes"){execSync(i,r),a(true);return}a(false);});})},te=gf.devDependencies,wf=async(i,t,e)=>{let r=Zr.includes(e)?[`typescript@${te.typescript}`,`esbuild@${te.esbuild}`]:[],o="";switch(e){case "mariadb":case "mysql":o=`mysql2@${te.mysql2}`;break;case "cockroachdb":case "postgres":o=`pg@${te.pg}`,r.push(`@types/pg@${te["@types/pg"]}`);break;case "sqlite":o=`sqlite3@${te.sqlite3}`,r.push(`@types/sqlite3@${te["@types/sqlite3"]}`);break;case "mongo":o=`mongodb@${te.mongodb}`,r.push(`@types/mongodb@${te["@types/mongodb"]}`);break;case "redis":o=`ioredis@${te.ioredis}`,r.push(`@types/ioredis@${te["@types/ioredis"]}`);break;case "mssql":o=`mssql@${te.mssql}`,r.push(`@types/mssql@${te["@types/mssql"]}`);break;case "oracledb":o=`oracledb@${te.oracledb}`,r.push(`@types/oracledb@${te["@types/oracledb"]}`);break;default:throw new Error(`Invalid database type: ${e}`)}if(o){let s=await bf(`${i} ${t} ${o}`,i,[o],{stdio:"inherit"});s&&g.info("Driver dependency installed successfully"),s||g.info("Driver dependency installation skipped");}let n=i==="deno"?"--dev":"-D";if(r.length){let s=await bf(`${i} ${t} ${r.join(" ")} ${n}`,i,r,{stdio:"inherit"});s&&g.info("Dev dependencies installed successfully"),s||g.info("Dev dependencies installation skipped");}};var Zr=["sqlite","mysql","postgres","mariadb","cockroachdb","mssql"],Xr=Zr.concat("mongodb","redis");async function Be(i,t){let{default:e}=await et(tt.resolve(process.cwd(),i));return e||(g.error(`The provided datasource file does not export a default export: ${i}`),process.exit(1)),mt.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}var ce=new Command;ce.command("init",{isDefault:false}).option("-t, --type [type]",`Type of the database to connect to, available types: ${Xr.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=Xr.join(", ");i.type||(g.error(`Database type is required (-t|--type), available types: ${t}`),process.exit(1)),Xr.includes(i.type)||(g.error(`Invalid database type: ${i.type}, available types: ${Xr.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]=Tf();g.info(`Package manager: ${e}`),g.info("Installing base dependencies"),await wf(e,r,i.type);let o=Jr.initTemplate(i.type);ne.existsSync("database")?g.info("database folder already exists, skipping"):ne.mkdirSync("database",{recursive:true}),ne.existsSync("database/index.ts")?g.info("database/index.ts file already exists, skipping"):ne.writeFileSync("database/index.ts",o),Zr.includes(i.type)&&!ne.existsSync("database/migrations")?ne.mkdirSync("database/migrations",{recursive:true}):g.info("database/migrations folder already exists or is not a sql database, skipping"),g.info("Initialization completed successfully");});ce.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 Be(t.datasource,t?.tsconfigPath);if(i){g.info("Executing SQL query directly from command line");try{await Hr(i,r,t?.out),g.info("SQL execution completed successfully"),process.exit(0);}catch(n){g.error(`SQL execution failed: ${n}`),process.exit(1);}}e||(g.error("No SQL statement or file provided"),process.exit(1)),g.info(`Reading SQL from file: ${e}`),e=tt.resolve(process.cwd(),e),ne.existsSync(e)||(g.error(`File not found: ${e}`),process.exit(1));let o=ne.readFileSync(e,"utf-8");g.info(`SQL file loaded successfully (${o.length} characters)`);try{await Hr(o,r,t?.out),g.info("SQL file execution completed successfully"),process.exit(0);}catch(n){g.error(`SQL file execution failed: ${n}`),process.exit(1);}});ce.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}`),Rl(i,t.javascript,e,t.table||i);});ce.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 Be(t.datasource,t?.tsconfigPath),r=t?.migrationPath||e.migrationConfig.path,o=t?.tsconfigPath||e.migrationConfig.tsconfig,n=t?.lock??e.migrationConfig.lock,s=t?.lockTimeout?parseInt(t.lockTimeout,10):e.migrationConfig.lockTimeout,a=t?.transactional??e.migrationConfig.transactional,l=false;try{if(n){if(g.info("Acquiring migration lock"),l=await e.acquireLock("hysteria_migration_lock",s),!l)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 St(e,i,r,o,a);}catch(u){throw console.error(u),u}finally{n&&l&&(g.info("Releasing migration lock"),await e.releaseLock("hysteria_migration_lock")||g.warn("Failed to release migration lock")),await e.disconnect();}});ce.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 Be(t.datasource,t?.tsconfigPath),r=t?.migrationPath||e.migrationConfig.path,o=t?.tsconfigPath||e.migrationConfig.tsconfig,n=t?.lock??e.migrationConfig.lock,s=t?.lockTimeout?parseInt(t.lockTimeout,10):e.migrationConfig.lockTimeout,a=t?.transactional??e.migrationConfig.transactional,l=false;try{if(n){if(g.info("Acquiring migration lock"),l=await e.acquireLock("hysteria_migration_lock",s),!l)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 vt(e,i,r,o,a);}catch(u){throw console.error(u),u}finally{n&&l&&(g.info("Releasing migration lock"),await e.releaseLock("hysteria_migration_lock")||g.warn("Failed to release migration lock")),await e.disconnect();}});ce.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 Be(i.datasource,i?.tsconfigPath),r=i?.migrationPath||e.migrationConfig.path,o=i?.tsconfigPath||e.migrationConfig.tsconfig,n=i?.lock??e.migrationConfig.lock,s=i?.lockTimeout?parseInt(i.lockTimeout,10):e.migrationConfig.lockTimeout,a=i?.transactional??e.migrationConfig.transactional,l=false;try{if(n){if(g.info("Acquiring migration lock for refresh operation"),l=await e.acquireLock("hysteria_migration_lock",s),!l)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 ro(e,!1,a):await vt(e,void 0,r,o,a),await St(e,void 0,r,o,a);}catch(u){console.error(u);}finally{n&&l&&(g.info("Releasing migration lock"),await e.releaseLock("hysteria_migration_lock")||g.warn("Failed to release migration lock")),await e.disconnect();}});ce.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 Be(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 o=await We.makeDiff(t);if((i.output==="raw"?"raw":"code")==="code"){let s=o.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(`
443
443
  // down()`);for(let u of s.down)console.log(u);process.exit(0);}ne.existsSync(e)||ne.mkdirSync(e,{recursive:!0});let a=await kt.generate(s,"code"),l=i?.javascript?".js":".ts";ne.writeFileSync(`${e}/${i?.name}${l}`,a),g.info(`Migration file created successfully: ${i?.name}${l}`);}else {let s=o.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);}ne.existsSync(e)||ne.mkdirSync(e,{recursive:!0});let a=await kt.generate(s,"raw"),l=i?.javascript?".js":".ts";ne.writeFileSync(`${e}/${i?.name}${l}`,a),g.info(`Migration file created successfully: ${i?.name}${l}`);}await t.disconnect(),process.exit(0);}catch(o){console.error(o),await t.disconnect(),process.exit(1);}});ce.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 Be(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 o=(await We.makeDiff(t)).getSqlStatements();if(o.length||(g.info("No new changes detected between database schema and models metadata"),await t.disconnect(),process.exit(0)),i.dry){g.info(`${o.length} SQL statement(s) would be executed:`);for(let n of o)console.log(n);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);}});ce.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)),tf(i,t.javascript,t.seederPath);});ce.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 Be(i.datasource,i?.tsconfigPath),e;i?.seederPath&&i.seederPath.length>0?e=i.seederPath.flatMap(o=>o.split(",").map(n=>n.trim())):e=[t.seederConfig.path];let r=i?.tsconfigPath||t.seederConfig.tsconfig;try{await rf(t,e,r),await t.disconnect(),g.info("Seeding completed successfully"),process.exit(0);}catch(o){console.error(o),await t.disconnect(),process.exit(1);}});ce.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 Be(i.datasource,i?.tsconfig);try{await fl(r,{outDir:i?.out||"./database/models",naming:e,dry:i?.dry||!1}),await r.disconnect(),process.exit(0);}catch(o){console.error(o),await r.disconnect(),process.exit(1);}});ce.parse(process.argv);