hysteria-orm 12.2.0 → 12.2.1
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 +1 -1
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +17 -17
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +39 -3
- package/lib/index.d.ts +39 -3
- package/lib/index.js +17 -17
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -256,7 +256,7 @@ ORDER BY ordinal_position`,bindings:[]}}},op=new ga;var ba=class{toSql(t){let e=
|
|
|
256
256
|
FROM pragma_table_info('${t.table}')
|
|
257
257
|
WHERE pk > 0
|
|
258
258
|
ORDER BY pk`,bindings:[]}}},pf=new Rl;var _l=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},ff=new _l;var Ml=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction,e.distinct),n=this.formatAlias(e.alias);return {sql:`${r.sql}${n}`,bindings:r.bindings}}formatColumn(t,e,r){if(typeof t=="string"){let o=new y(this.model).formatStringColumn("sqlite",t),s=o;return e&&(s=`${e.toLowerCase()}(${r?"DISTINCT ":""}${o})`),{sql:s,bindings:[]}}if(Array.isArray(t)&&t.length>0){let s=new b(this.model,"sqlite").parse(t),a=`(${s.sql})`;return e&&(a=`${e.toLowerCase()}${a}`),{sql:a,bindings:s.bindings}}if(!Array.isArray(t)){let s=new b(this.model,"sqlite").parse([t],void 0,true),a=`(${s.sql})`;return e&&(a=`${e.toLowerCase()}${a}`),{sql:a,bindings:s.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let u=new y(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${u})`:u}let l=`(${new b(this.model,"sqlite").parse([o]).sql})`;return e&&(l=`${e.toLowerCase()}${l}`),l}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,n)=>{let o=t.slice(0,n),s=o.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=o.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},yf=new Ml;var xl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new y(this.model).formatStringColumn("sqlite",e.column),n=te.from(e.jsonPath),o="";switch(e.jsonOperator){case "extract":o=this.buildExtractSql(r,n);break;case "extract_text":o=this.buildExtractTextSql(r,n);break;case "array_length":o=this.buildArrayLengthSql(r,n);break;case "object_keys":o=this.buildObjectKeysSql(r,n);break;case "raw":o=e.column;break}return {sql:this.formatWithAlias(o,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},hf=new xl;var Ol=class{toSql(t){let e=t,r=je(this.dbType,e);if(r!==void 0)return {sql:r,bindings:[]};let n=this.renderToken(e.fn);if(n!==void 0)return {sql:n,bindings:[]};let o=e.args.map(s=>s instanceof x?s.rawValue:s instanceof P?this.toSql(s).sql:typeof s=="number"?String(s):`'${s}'`).join(", ");return {sql:`${e.fn}(${o})`,bindings:[]}}renderToken(t){switch(t){case "$uuid":return "lower(hex(randomblob(16)))";case "$now":case "$currentTimestamp":return "current_timestamp";default:return}}},gf=new Ol;var Dl=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new y(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},bf=new Dl;var Al=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),n=Array.isArray(e.query)?e.query:[e.query],o=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(n.filter(Boolean),e.currParamIndex);return {sql:o.sql,bindings:o.bindings}}},Tf=new Al;var $l=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new y(this.model),n=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:n,bindings:[]};let o=[],s=e.currParamIndex,a=e.columns.map((l,u)=>{let d=e.values[u],c=r.formatStringColumn("sqlite",l);if(d instanceof x)return `${c} = ${d.rawValue}`;if(d instanceof N){let m=new b(this.model,"sqlite").parse([d],s,true);return o.push(...m.bindings),s+=m.bindings.length,`${c} = ${m.sql}`}return o.push(d),`${c} = ?`}).join(", ");return {sql:`${n} set ${a}`,bindings:o}}},wf=new $l;var vl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",n=[];if(this.isRawNode(e.value)){let o=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${o}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new y(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,n=e.value;else {let o=e.value.map(s=>"?").join(", ");r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${o})`,n=e.value;}else if(e.value instanceof P){let o=new b(this.model,"sqlite").parse([e.value],1,true).sql;r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${o}`,n=[];}else if(e.operator.includes("null"))r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new y(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,n=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new y(this.model).formatStringColumn("sqlite",t):t}},Sf=new vl;var Il=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"sqlite"),{sql:n,bindings:o}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${n})`,bindings:o}}},Nf=new Il;var Pl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",n=[],o=new y(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${o}) = json(?)`,n=[JSON.stringify(e.value)];break;case "contains":r=`json(${o}) = json(?)`,n=[JSON.stringify(e.value)];break;case "not contains":r=`json(${o}) = json(?)`,n=[JSON.stringify(e.value)];break;case "path":{let s=te.from(e.path??"");r=`json_extract(${o}, '${s.toSqlite()}') ${e.comparisonOperator??"="} ?`,n=[e.value];break}case "subset":case "has none":throw new S("WhereJsonInterpreter::unsupported","NOT_SUPPORTED_IN_SQLITE");case "raw":r=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:n}}},qf=new Pl;var El=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:n}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:n}}handleObjectSubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:n}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:n}}},Cf=new El;var Bl=class{toSql(t){let e=t,r=new y(this.model),n=s=>r.formatStringColumn("sqlite",s),o=[];return e.partitionBy.length&&o.push(`partition by ${e.partitionBy.map(n).join(", ")}`),e.orderBy.length&&o.push(`order by ${e.orderBy.map(s=>s.order?`${n(s.column)} ${s.order}`:n(s.column)).join(", ")}`),{sql:`${e.fn}() over (${o.join(" ")})`,bindings:[]}}},Rf=new Bl;var kl=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),n=Array.isArray(e.body)?e.body:[e.body],o=r.parse(n.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${o.sql})`,bindings:o.bindings}}},_f=new kl;var Kl={mssql:{alter_table:{add_column:Iu,add_constraint:Pu,add_primary_key:Eu,alter_column_type:Bu,alter_table:Ku,drop_column:Qu,drop_constraint:Lu,drop_default:Wu,drop_not_null:ju,drop_primary_key:Fu,rename_column:Uu,rename_table:Vu,set_default:Hu,set_not_null:zu,set_table_options:Gu},column:{column_type:Yu},comment:{comment:Zu},constraint:{after:Xu,constraint:ed},create_table:{create_table:td},delete:{delete:rd},distinct:{distinct:nd,distinct_on:od},drop_table:{drop_table:sd},extension:{create_extension:id},from:{from:ad},group_by:{group_by:ld},having:{having:ud},index_op:{create_index:dd,drop_index:cd},insert:{insert:md},join:{join:pd},json_mutation:{json_mutation:Td},limit:{limit:wd},lock:{lock:Sd},offset:{offset:Nd},on_duplicate:{on_duplicate:qd},order_by:{order_by:Cd},raw:{raw:Rd},returning:{returning:_d},schema:{check_constraint_info:Md,foreign_key_info:xd,get_column_listing:Od,get_tables:Dd,has_check_constraint:Ad,has_column:$d,has_index:vd,has_primary_key:Id,has_table:Pd,index_info:Ed,primary_key_info:Bd,table_info:kd},select:{select:Kd,select_json:Qd},sqlfunc:{sqlfunc:Ld},truncate:{truncate:Wd},union:{union:jd},update:{update:Fd},where:{where:Ud,where_group:Vd,where_json:Jd,where_subquery:Hd},window:{window:zd},with:{with:Gd}},mysql:{alter_table:{add_column:Yd,add_constraint:Zd,add_primary_key:Xd,alter_column_type:ec,alter_table:tc,drop_column:rc,drop_constraint:nc,drop_default:oc,drop_not_null:sc,drop_primary_key:ic,rename_column:ac,rename_table:lc,set_default:uc,set_not_null:dc,set_table_options:cc},column:{column_type:mc},comment:{comment:pc},constraint:{after:fc,constraint:yc},create_table:{create_table:hc},delete:{delete:gc},distinct:{distinct:bc,distinct_on:Tc},drop_table:{drop_table:wc},extension:{create_extension:Sc},from:{from:Nc},group_by:{group_by:qc},having:{having:Cc},index_op:{create_index:Rc,drop_index:_c},insert:{insert:Mc},join:{join:xc},json_mutation:{json_mutation:Oc},limit:{limit:Dc},lock:{lock:Ac},offset:{offset:$c},on_duplicate:{on_duplicate:vc},order_by:{order_by:Ic},raw:{raw:Pc},returning:{returning:Ec},schema:{check_constraint_info:Bc,foreign_key_info:kc,get_column_listing:Kc,get_tables:Qc,has_check_constraint:Lc,has_column:Wc,has_index:jc,has_primary_key:Fc,has_table:Uc,index_info:Vc,primary_key_info:Jc,table_info:Hc},select:{select:zc,select_json:Gc},sqlfunc:{sqlfunc:Yc},truncate:{truncate:Zc},union:{union:Xc},update:{update:em},where:{where:tm,where_group:rm,where_json:nm,where_subquery:om},window:{window:sm},with:{with:im}},postgres:{alter_table:{add_column:am,add_constraint:lm,add_primary_key:um,alter_column_type:dm,alter_table:cm,drop_column:mm,drop_constraint:pm,drop_default:fm,drop_not_null:ym,drop_primary_key:hm,rename_column:gm,rename_table:bm,set_default:Tm,set_not_null:wm,set_table_options:Sm},column:{column_type:Nm},comment:{comment:qm},constraint:{after:Cm,constraint:Rm},create_table:{create_table:_m},delete:{delete:Mm},distinct:{distinct:xm,distinct_on:Om},drop_table:{drop_table:Dm},extension:{create_extension:Am},from:{from:$m},group_by:{group_by:vm},having:{having:Im},index_op:{create_index:Pm,drop_index:Em},insert:{insert:Bm},join:{join:km},json_mutation:{json_mutation:Km},limit:{limit:Qm},lock:{lock:Lm},offset:{offset:Wm},on_duplicate:{on_duplicate:jm},order_by:{order_by:Fm},raw:{raw:Um},returning:{returning:Vm},schema:{check_constraint_info:Jm,foreign_key_info:Hm,get_column_listing:zm,get_tables:Gm,has_check_constraint:Ym,has_column:Zm,has_index:Xm,has_primary_key:ep,has_table:tp,index_info:rp,primary_key_info:np,table_info:op},select:{select:sp,select_json:ip},sqlfunc:{sqlfunc:ap},truncate:{truncate:lp},union:{union:up},update:{update:dp},where:{where:cp,where_group:mp,where_json:pp,where_subquery:fp},window:{window:yp},with:{with:hp}},sqlite:{alter_table:{add_column:gp,add_constraint:bp,alter_column_type:Tp,alter_table:wp,drop_column:Sp,drop_constraint:Np,drop_default:qp,drop_not_null:Cp,drop_primary_key:Rp,rename_column:_p,rename_table:Mp,set_default:xp,set_not_null:Op,set_table_options:Dp},column:{column_type:Ap},comment:{comment:$p},constraint:{after:vp,constraint:Ip},create_table:{create_table:Pp},delete:{delete:Ep},distinct:{distinct:Bp,distinct_on:kp},drop_table:{drop_table:Kp},extension:{create_extension:Qp},from:{from:Lp},group_by:{group_by:Wp},having:{having:jp},index_op:{create_index:Fp,drop_index:Up},insert:{insert:Vp},join:{join:Jp},json_mutation:{json_mutation:Hp},limit:{limit:zp},lock:{lock:Gp},offset:{offset:Yp},on_duplicate:{on_duplicate:Zp},order_by:{order_by:Xp},raw:{raw:ef},returning:{returning:tf},schema:{check_constraint_info:rf,foreign_key_info:nf,get_column_listing:of,get_tables:sf,has_check_constraint:af,has_column:lf,has_index:uf,has_primary_key:df,has_table:cf,index_info:mf,primary_key_info:pf,table_info:ff},select:{select:yf,select_json:hf},sqlfunc:{sqlfunc:gf},truncate:{truncate:bf},union:{union:Tf},update:{update:wf},where:{where:Sf,where_group:Nf,where_json:qf,where_subquery:Cf},window:{window:Rf},with:{with:_f}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let n=t.find(R=>!!R&&R.folder==="distinctOn"),o=!n&&t.find(R=>!!R&&R.folder==="distinct"),s=t.filter(R=>!!R&&R.folder==="comment"&&R.isHint).map(R=>this.renderNode(R)).filter(R=>R.length>0).join(" "),a=this.dbType==="mssql"?t.find(R=>!!R&&R.folder==="lock")??null:null,l=a?this.getMssqlTableHints(a):"",u=t.filter(R=>R!==null&&R.folder!=="distinct"&&R.folder!=="distinctOn"&&!(R.folder==="comment"&&R.isHint)),d=u.some(R=>R.folder==="offset"),c=u.some(R=>R.folder==="order_by"),m=u.find(R=>R.folder==="limit"),p=u.find(R=>R.folder==="offset"),h=this.dbType==="mssql"&&m&&!d&&!c,f=this.dbType==="mssql"&&!h&&(m||p),T=[],w=[],q=null;h&&m&&w.push(m.limit);for(let R=0;R<u.length;R++){let $=u[R];if(h&&$.folder==="limit"||f&&($.folder==="limit"||$.folder==="offset"))continue;$.currParamIndex=e+w.length;let A=Kl[this.mapCommonDbType(this.dbType)][$.folder][$.file];if(!A)throw new Error(`Interpreter not found for ${this.dbType} ${$.keyword}`);A.model=this.model,A.dbType=this.dbType;let O=A.toSql($);if(!O.sql||!O.sql.trim().length)continue;let K=u[R+1],v=!K||K.keyword!==$.keyword?"":K.chainsWith;if($.folder==="lock"||$.folder==="on_duplicate"||$.folder==="returning"||$.folder==="schema"||$.folder==="comment"){T.push(`${O.sql}${v}`),w.push(...O.bindings),q=$.keyword;continue}if(q!==$.keyword||$.canKeywordBeSeenMultipleTimes){if(r)T.push(`${O.sql}${v}`);else {let ne=$.keyword;if($.folder==="with"&&this.dbType!=="mssql"){let _e=R,Me=false;for(;_e<u.length&&u[_e].keyword===$.keyword;){let uu=u[_e];if(uu.folder==="with"&&uu.clause==="recursive"){Me=true;break}_e++;}Me&&(ne=`${ne} recursive`);}let Ye=s?`${s} `:"";if(ne==="select"){let _e=h?`top (@${e}) `:"";if(n){let Me=Array.isArray(n.columns)?n.columns.join(", "):"";T.push(`select ${_e}${Ye}distinct on (${Me}) ${O.sql}${v}`);}else o?T.push(`select ${_e}${Ye}distinct ${O.sql}${v}`):T.push(`select ${_e}${Ye}${O.sql}${v}`);}else ne==="from"&&l?T.push(`${ne} ${O.sql}${l}${v}`):T.push(`${ne} ${O.sql}${v}`);}q=$.keyword;}else T.push(`${O.sql}${v}`);w.push(...O.bindings);}if(f){c||T.push("order by (select null)");let R=p?.offset??0;w.push(R);let A=`offset @${e+w.length-1} rows`;if(m){w.push(m.limit);let O=e+w.length-1;A+=` fetch next @${O} rows only`;}T.push(A);}return {sql:T.join(" "),bindings:w}}renderNode(t){let e=Kl[this.mapCommonDbType(this.dbType)][t.folder][t.file];if(!e)throw new Error(`Interpreter not found for ${this.dbType} ${t.keyword}`);return e.model=this.model,e.dbType=this.dbType,e.toSql(t).sql}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}getMssqlTableHints(t){let e=[];switch(t.lockType){case "UPDATE":e.push("UPDLOCK");break;case "SHARE":e.push("HOLDLOCK");break;case "NO_KEY_UPDATE":e.push("UPDLOCK");break;case "KEY_SHARE":e.push("HOLDLOCK");break}return t.skipLocked&&e.push("READPAST"),t.noWait&&e.push("NOWAIT"),e.length>0?` with (${e.join(", ")})`:""}};var Tr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var wr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Sr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Nr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var qr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Cr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_table";this.table=e;}};var Rr=class extends N{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_column";this.table=e,this.column=r;}};var _r=class extends N{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_index";this.table=e,this.index=r;}};var Mr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_primary_key";this.table=e;}};var xr=class extends N{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_check_constraint";this.table=e,this.constraint=r;}};var Or=class extends N{constructor(){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="get_tables";}};var Dr=class extends N{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="get_column_listing";this.table=e;}};var Ar=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var we=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var wt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var $r=class extends N{constructor(e,r,n={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=n;}};var fe=class extends N{constructor(e,r=[],n=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=n;}};var vr=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var Se=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var Qt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Ir=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var St=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var Pr=class extends N{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Er=class extends N{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Br=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var Nt=class extends N{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var V=class extends N{constructor(e,r={},n=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=n;}};var kr=class extends N{constructor(e,r=[],n=[],o=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=n,this.ifNotExists=o,s&&Object.assign(this,s);}};var Kr=class extends N{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var Qr=class extends N{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var Lr=class extends N{constructor(e,r,n,o=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=n,this.unique=o;}};var Wr=class extends N{constructor(e,r,n){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=n??false;}};var qt=class extends N{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};function Ch(i){return i.endsWith("ies")?i.slice(0,-3)+"y":i.endsWith("sses")||i.endsWith("shes")||i.endsWith("ches")||i.endsWith("xes")||i.endsWith("zes")?i.slice(0,-2):i.endsWith("s")&&!i.endsWith("ss")?i.slice(0,-1):i}var jr=Symbol("columns"),Ct=Symbol("primaryKey"),Ql=Symbol("relations"),Mf=Symbol("indexes"),xf=Symbol("uniques"),Of=Symbol("checks"),Ll=i=>`${Ch(i)}_id`,Wl=(i,t)=>`idx_${i}_${t}`,Ne=(i,t)=>`uq_${i}_${t}`,Z=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,qe=(i,t)=>`pk_${i}_${t}`;var k=class extends N{constructor(e,r,n={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=n.length,this.precision=n.precision,this.scale=n.scale,this.enumValues=n.enumValues,this.withTimezone=n.withTimezone,this.autoIncrement=n.autoIncrement,this.autoCreate=n.autoCreate,this.autoUpdate=n.autoUpdate,this.collate=n.collate,this.isRawValue=n.isRawValue??false,this.unsigned=n.unsigned,this.zerofill=n.zerofill;}};var Lt=class extends N{constructor(e,r=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="comment";this.file="comment";this.value=e,this.isHint=r;}};var Xe=class extends N{constructor(e,r=false,n=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=n;}};var Fr=class extends N{constructor(e,r=[],n=[]){super("window");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="window";this.file="window";this.fn=e,this.partitionBy=r,this.orderBy=n;}};function Df(i){return i?Array.isArray(i)?i:[i]:[]}function Af(i){return i?(Array.isArray(i)?i:[i]).map(e=>typeof e=="string"?{column:e}:e):[]}var Ie=class extends N{constructor(e,r=false,n="union"){super(r?`${n} all`:n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r,this.type=n;}};var et=class extends N{constructor(e,r,n){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=n,this.clause=e;}};var Fe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Ur=class extends N{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var Vr=class extends Fe{constructor(t,e,r,n,o=[],s="create_table"){super(e),this.columnNode=r,this.tableName=n,this.namedConstraints=o,this.context=s,this.sqlType=t;}primaryKey(t){let e=qe(this.tableName,C(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new V("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new V("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){this.columnNode.isForeignKey=true;let[r,n]=t.split("."),o=n.split(","),s=e?.constraintName??Z(this.tableName??"",C(this.columnNode.column),o[0]);return this.context==="alter_table"?(this.nodes.push(new V("foreign_key",{columns:[C(this.columnNode.column)],references:{table:r,columns:o},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new V("foreign_key",{columns:[C(this.columnNode.column)],references:{table:r,columns:o},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}unsigned(){return this.columnNode.unsigned=true,this}zerofill(){return this.columnNode.zerofill=true,this}notNullable(){return this.nodes.push(new V("not_null",{columns:[C(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new V("null",{columns:[C(this.columnNode.column)]})),this}default(t){let e;return t instanceof x||t instanceof P?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new V("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new V("unique",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName??Ne(this.tableName??"",C(this.columnNode.column))})),this):(this.namedConstraints.push(new V("unique",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName||Ne(this.tableName??"",C(this.columnNode.column))})),this)}check(t,e){let r=C(this.columnNode.column),n=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new V("check",{columns:[r],checkExpression:t,constraintName:n})),this):(this.namedConstraints.push(new V("check",{columns:[r],checkExpression:t,constraintName:n})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new Ur(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.isInlineSqlitePrimaryKey()?this:(this.nodes.push(new V("primary_key",{columns:[C(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this)}isInlineSqlitePrimaryKey(){let t=(this.columnNode.dataType??"").toLowerCase();return t==="bigincrement"?true:(t==="integer"||t==="bigint"||t==="int")&&!!this.columnNode.autoIncrement}};var tt=class extends Fe{constructor(e,r,n,o){super(r);this.context="create_table";this.tableName=n,this.namedConstraints=[],this.context=o??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new Vr(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new x(e)}char(e,r=1){let n=new k(e,"char",{length:r});return this.build(n)}varchar(e,r=255){let n=new k(e,"varchar",{length:r});return this.build(n)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let n=new k(e,r);return this.build(n)}longtext(e){return this.text(e,"longtext")}mediumtext(e){return this.text(e,"mediumtext")}tinytext(e){return this.text(e,"tinytext")}uuid(e){let r=new k(e,"uuid");return this.build(r)}ulid(e){let r=new k(e,"ulid");return this.build(r)}integer(e,r=255){let n=new k(e,"integer",{length:r});return this.build(n)}tinyint(e,r=255){let n=new k(e,"tinyint",{length:r});return this.build(n)}smallint(e,r=255){let n=new k(e,"smallint",{length:r});return this.build(n)}mediumint(e,r=255){let n=new k(e,"mediumint",{length:r});return this.build(n)}biginteger(e,r=255){let n=new k(e,"bigint",{length:r});return this.build(n)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let n=new k(e,"float",{precision:r});return this.build(n)}double(e,r=10){let n=new k(e,"double",{precision:r});return this.build(n)}real(e,r=10){let n=new k(e,"real",{precision:r});return this.build(n)}decimal(e,r=10,n=2){let o=new k(e,"decimal",{precision:r,scale:n});return this.build(o)}numeric(e,r=10,n=2){let o=new k(e,"numeric",{precision:r,scale:n});return this.build(o)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let n=new k(e,"date",{precision:r});return this.build(n)}time(e,r){let n=new k(e,"time",{precision:r});return this.build(n)}year(e){let r=new k(e,"year");return this.build(r)}datetime(e,r){let n=new k(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(n)}timestamp(e,r){let n=new k(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(n)}boolean(e){let r=new k(e,"boolean");return this.build(r)}binary(e){let r=new k(e,"binary");return this.build(r)}varbinary(e,r=255){let n=new k(e,"varbinary",{length:r});return this.build(n)}blob(e){let r=new k(e,"blob");return this.build(r)}tinyblob(e){let r=new k(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new k(e,"mediumblob");return this.build(r)}longblob(e){let r=new k(e,"longblob");return this.build(r)}json(e){let r=new k(e,"json");return this.build(r)}jsonb(e){let r=new k(e,"jsonb");return this.build(r)}enum(e,r){let n=new k(e,"enum",{enumValues:r});return this.build(n)}custom(e,r,n){let o=new k(e,r,{length:n});return this.build(o)}rawColumn(e){let r=new k(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new k(e,"geometry");return this.build(r)}point(e){let r=new k(e,"point");return this.build(r)}linestring(e){let r=new k(e,"linestring");return this.build(r)}polygon(e){let r=new k(e,"polygon");return this.build(r)}multiPoint(e){let r=new k(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Jr=class extends Fe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new x(t)}addColumn(t){let e=[],r=new tt(this.sqlType,e,this.table,"alter_table"),n=t(r);if(!e.length)return;let o=r.getNamedConstraints(),s=e.filter(c=>c.folder==="column");if(e=e.concat(o),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=n.getNodes().filter(c=>{let m=c;return m.constraintType==="not_null"||m.constraintType==="null"||m.constraintType==="default"}),u=new Ar(a);u.inlineConstraints=l,this.nodes.push(u),n.getNodes().filter(c=>{let m=c;return m.constraintType==="unique"||m.constraintType==="foreign_key"||m.constraintType==="primary_key"}).forEach(c=>{this.nodes.push(new we(c));});}alterColumn(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new tt(this.sqlType,e,this.table,"alter_table"),n=t(r);if(!e.length)return;let o=e.filter(p=>p.folder==="column");if(o.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=o[0],a=C(s.column),l=n.getNodes().find(p=>p.constraintType==="null"),d=n.getNodes().find(p=>p.constraintType==="not_null")||l,c=n.getNodes().find(p=>p.constraintType==="default"),m={};d&&(m.nullable=d.constraintType==="null"),c&&(c.defaultValue===void 0||c.defaultValue===null||c.defaultValue==="NULL"?m.dropDefault=true:m.default=c.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(m.collate=s.collate),this.nodes.push(new $r(C(a),s,m)),d&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(d.constraintType==="not_null"?this.nodes.push(new Br(C(a))):d.constraintType==="null"&&this.nodes.push(new Ir(C(a)))),c&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(c.defaultValue===void 0||c.defaultValue===null||c.defaultValue==="NULL"?this.nodes.push(new Qt(C(a))):this.nodes.push(new Er(C(a),c.defaultValue))),n.getNodes().forEach(p=>{let h=p;switch(h.constraintType){case "primary_key":this.addPrimaryKey(C(a));break;case "unique":this.unique(C(a),{constraintName:h.constraintName});break;case "foreign_key":this.foreignKey(C(a),h.references?.table??"",C(h.references?.columns?.[0]??""),{constraintName:h.constraintName,onDelete:h.onDelete,onUpdate:h.onUpdate});break}});}dropColumn(t){this.nodes.push(new vr(t));}renameColumn(t,e){this.nodes.push(new Pr(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Qt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new wt([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new we(new V(...t)));}foreignKey(t,e,r,n){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new we(new V("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:n?.constraintName??Z(this.table,t,r),onDelete:n?.onDelete,onUpdate:n?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new we(new V("unique",{columns:[t],constraintName:e?.constraintName??Ne(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=Z(this.table,t,e);this.nodes.push(new Se(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new S("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??Ne(this.table,t);this.nodes.push(new Se(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Se(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new S("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new S("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new St(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",n=this.sqlType==="mssql";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new Nt(t)):r?this.nodes.push(new Nt(t)):n&&this.nodes.push(new Nt(t)),this)}};var ce=class{constructor(t){if(this.sqlType=t||E.DB_TYPE,!this.sqlType)throw new S("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new x(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!ae.existsSync(t))throw new S("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=yt.basename(t),r=yt.extname(e);if(r!==".sql"&&r!==".txt")throw new S("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let o=ae.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of o)this.rawQuery(s);}createTable(t,e,r){let n=new tt(this.sqlType,[],t);e(n);let o=n.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?n.getMysqlOptions()||{}:{}},l=new kr(t,o,n.getNamedConstraints(),r?.ifNotExists,a),u=s.parse([l]).sql,d=u.startsWith("create table")?u:`create table ${u}`;this.rawQuery(d),this.generateAutoUpdateTriggers(t,o);}alterTable(t,e){let r=[],n=new Jr(t,r,this.sqlType);if(e(n),!r.length)return;let o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"}),s=[],a=()=>{if(!s.length)return;let u=new fe(t,s),d=o.parse([u]).sql;if(!d||!d.trim())return;let c=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(c),s=[];};for(let u of r)u.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(u);a();let l=r.filter(u=>u.file==="add_column").map(u=>u.column);this.generateAutoUpdateTriggers(t,l);}dropTable(t,e=false){let r=new Kr(t,e),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}renameTable(t,e){let r=new fe(t,[new gt(e)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}truncateTable(t){let e=new qt(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r={}){Array.isArray(e)||(e=[e]);let n=r.constraintName||Wl(t,e.join("_")),o=new Lr(t,e,n),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([o]).sql);}dropIndex(t,e){let r=new Wr(t,e),n=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}addPrimaryKey(t,e){let r=new fe(t,[new wt(e)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}addUnique(t,e,r){let n=Array.isArray(e)?e:[e],o=r?.constraintName??Ne(t,n.join("_")),s=new V("unique",{columns:n,constraintName:o}),a=new fe(t,[new we(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let n=Z(t,e,r),o=new Se(n),s=new fe(t,[o]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let n=Array.isArray(e)?Ne(t,e.join("_")):Ne(t,e),o=r?.constraintName??n,s=new Se(o),a=new fe(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new St,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new V(...e),n=new fe(t,[new we(r)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([n]).sql);}dropConstraint(t,e){let r=new Se(e),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}addCheck(t,e,r){let n=r?.constraintName??`chk_${t}_custom`.substring(0,63),o=new V("check",{checkExpression:e,constraintName:n}),s=new fe(t,[new we(o)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new Se(e),n=new fe(t,[r]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([n]).sql);}createExtension(t,e=true){let r=new Qr(t,e),n=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(n=>n.folder==="column"&&n.autoUpdate===true).map(n=>C(n.column));for(let n of r){let o=this.getAutoUpdateTriggerSql(t,n);for(let s of o)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];default:return []}}generateAstInstance(t){return new b(t,this.sqlType)}};var Hr,If,Wt=class{constructor(t,e){fu(this,Hr);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new ce(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=yu(this,Hr,If).call(this)),this.executionPromise.then(t,e)}rawStatement(t){return this.schema.rawStatement(t)}rawQuery(t){return this.schema.rawQuery(t),this}createTable(t,e,r){return this.schema.createTable(t,e,r),this}alterTable(t,e){return this.schema.alterTable(t,e),this}dropTable(t,e=false){return this.schema.dropTable(t,e),this}renameTable(t,e){return this.schema.renameTable(t,e),this}truncateTable(t){return this.schema.truncateTable(t),this}createIndex(t,e,r){return this.schema.createIndex(t,e,r),this}dropIndex(t,e){return this.schema.dropIndex(t,e),this}addPrimaryKey(t,e){return this.schema.addPrimaryKey(t,e),this}addUnique(t,e,r){return this.schema.addUnique(t,e,r),this}addConstraint(t,e,...r){return this.schema.addConstraint(t,e,...r),this}dropPrimaryKey(t){return this.schema.dropPrimaryKey(t),this}dropForeignKey(t,e,r){return this.schema.dropForeignKey(t,e,r),this}dropUnique(t,e,r){return this.schema.dropUnique(t,e,r),this}dropConstraint(t,e){return this.schema.dropConstraint(t,e),this}createExtension(t,e=true){return this.schema.createExtension(t,e),this}toQuery(){let t=this.schema.queryStatements;return t.length===1?t[0]:t}toQueries(){return [...this.schema.queryStatements]}toString(){let t=this.schema.queryStatements;return t.length===1?t[0]||"":t.join(`;
|
|
259
|
-
`)}async execute(){if(this.state!=="executed"){if(this.state==="failed")throw this.executionError;return this.then()}}isExecuted(){return this.state==="executed"}isPending(){return this.state==="pending"}hasFailed(){return this.state==="failed"}async hasTable(t){return this.dataSource.hasTable(t)}async hasColumn(t,e){return this.dataSource.hasColumn(t,e)}async hasColumns(t,...e){return this.dataSource.hasColumns(t,...e)}async hasIndex(t,e){return this.dataSource.hasIndex(t,e)}async hasPrimaryKey(t){return this.dataSource.hasPrimaryKey(t)}async hasUnique(t,e){return this.dataSource.hasUnique(t,e)}async hasForeignKey(t,e){return this.dataSource.hasForeignKey(t,e)}async hasCheckConstraint(t,e){return this.dataSource.hasCheckConstraint(t,e)}async getTables(){return this.dataSource.getTables()}async getColumnListing(t){return this.dataSource.getColumnListing(t)}dropTableIfExists(t){return this.schema.dropTable(t,true),this}async dropIndexIfExists(t,e){if(await this.dataSource.hasIndex(e,t)){let n=new ce(this.dataSource.getDbType());n.dropIndex(t,e);let o=n.queryStatements[0];o&&await this.dataSource.rawQuery(o);}}renameColumn(t,e,r){return this.schema.alterTable(t,n=>{n.renameColumn(e,r);}),this}};Hr=new WeakSet,If=async function(){try{this.state="pending";let t=this.schema.queryStatements;if(!t.length){this.state="executed";return}for(let e of t)await this.dataSource.rawQuery(e);this.state="executed";}catch(t){throw this.state="failed",this.executionError=t,t}};var Oe=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var zr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}buildDropDependencies(t){let e=new Map,r=new Map,n=new Map;for(let o of t.relationsToDrop||[]){let s=`${o.table}.${o.relation.name}`,a=[];if(o.relation.referencedTable&&a.push(`table.${o.relation.referencedTable}`),o.relation.referencedColumns)for(let l of o.relation.referencedColumns)a.push(`column.${o.relation.referencedTable}.${l}`);e.set(s,a);}for(let o of t.tablesToDrop||[]){let s=`table.${o.table}`,a=[];for(let l of this.models){let u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===o.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let o of t.columnsToDrop||[]){let s=`column.${o.table}.${o.column}`,a=[],l=this.models.find(u=>u.table===o.table);if(l){let u=l.getColumns().find(d=>d.databaseName===o.column);if(u){u.isPrimary&&a.push(`pk.${o.table}`);let d=l.getRelations();for(let c of d)c.columnName===u.columnName&&a.push(`fk.${o.table}.${c.constraintName}`);}}n.set(s,a);}return {foreignKeys:e,tables:r,constraints:n}}topologicalSortReverse(t,e){let r=new Set,n=new Set,o=[],s=a=>{if(n.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;n.add(a);let l=e(a);for(let u of l)s(u);n.delete(a),r.add(a),o.push(a);};for(let a of t.keys())r.has(a)||s(a);return o}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],n=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of n){let[a,l]=s.split("."),u=t.relationsToDrop?.find(d=>d.table===a&&d.relation.name===l);u&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:u,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(u)});}let o=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let u of l)u.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):u.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of o){let a=s.replace("table.",""),l=t.tablesToDrop?.find(u=>u.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let n=[],o=this.models.find(s=>s.table===r.table);if(o){let s=o.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&n.push(`PRIMARY KEY on ${r.table}`);let a=o.getRelations();for(let l of a)l.columnName===s.columnName&&n.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,n);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let n=this.models.find(o=>o.table===r.table);n&&n.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,n=>{n.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Fl=i=>String(i??"").replace(/::[a-z_ ]+$/i,"").replace(/[()\s]/g,"").toLowerCase(),Rh=/^(current[ _]?timestamp\d*|now\d*|getdate\d*|localtimestamp\d*|localtime\d*)$/,_h={postgres:i=>i.includes("nextval"),cockroachdb:i=>i.includes("unique_rowid")},Mh={postgres:["gen_random_uuid"],cockroachdb:["gen_random_uuid"],mysql:["uuid"],mariadb:["uuid"],mssql:["newid"],sqlite:["lower(hex(randomblob(16)))"]},Ef=(i,t)=>(Mh[i]??[]).includes(Fl(t)),Rt=(i,t)=>!!i.autoCreate&&Rh.test(Fl(t)),_t=(i,t,e)=>{if(t.type!=="increment"&&t.type!=="bigIncrement")return false;let r=_h[i];return r?r(Fl(e)):false};var Gr=class Gr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new zr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,n=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),o=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...n].filter(l=>o.has(l)));return e.filter(l=>{let u=r(l);return u?!(s.has(u)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let n=this.sql.schema().createTable(r.table,o=>{for(let s of r.columns){if(Array.isArray(s.type)){o.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,o,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[n]});}for(let r of t.columnsToAdd){let n=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:n});}return e}generateConstraintCreationOperations(t){let e=[];for(let n of t.uniquesToDrop||[]){let o=this.sql.schema().alterTable(n.table,s=>{s.dropConstraint(n.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:o});}let r=new Set((t.uniquesToDrop||[]).map(n=>n.name));for(let n of t.indexesToDrop){if(r.has(n.index))continue;let o=new ce(this.sql.getDbType());o.dropIndex(n.index,n.table);let s=o.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[s]});}for(let n of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===n.table)?.getColumns().find(u=>u.columnName===n.columns[0])?.primaryKeyConstraintName||qe(n.table,n.columns[0]),l=this.sql.schema().alterTable(n.table,u=>{let d=a||qe(n.table,n.columns[0]);u.addConstraint("primary_key",{columns:[n.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:a,data:n,dependencies:[`table.${n.table}`],sqlStatements:l});}for(let n of t.relationsToAdd){if(n.relation.type==="manyToMany")continue;let o=this.generateAddRelationViaAlter(n),s=this.computeFkConstraintName(n);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:s,data:n,dependencies:this.getForeignKeyDependencies(n),sqlStatements:o});}for(let n of t.uniquesToAdd||[]){let o=this.models.find(l=>l.table===n.table),s=(n.columns||[]).map(l=>o?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(n.table,l=>{l.addConstraint("unique",{columns:s,constraintName:n.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name||"mandatory",data:n,dependencies:[`table.${n.table}`],sqlStatements:a});}for(let n of t.indexesToAdd){let o=this.generateCreateIndexSql(n);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[o]});}for(let n of t.checksToDrop||[]){let o=new ce(this.sql.getDbType());o.dropCheck(n.table,n.name);let s=o.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}for(let n of t.checksToAdd||[]){let o=new ce(this.sql.getDbType());o.addCheck(n.table,n.expression,{constraintName:n.name});let s=o.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=C(t.relation.constraintName);if(e)return e;let r=t.table;t.relation.type==="belongsTo"?r=t.relation.model().table:t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(r=C(t.relation.manyToManyOptions.throughModel));let o=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=o.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=o.find(l=>l.columnName===s)?.databaseName||s,Z(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let n=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:n});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let n=t.relation.model();e.push(`table.${n.table}`);let o=n.primaryKey||"id",s=n.getColumns().find(a=>a.columnName===o);s&&e.push(`column.${n.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let n=C(t.relation.manyToManyOptions.throughModel);e.push(`table.${n}`);}e.push(`table.${t.table}`);let r=this.models.find(n=>n.table===t.table);if(r){let n=r.getColumns().find(o=>o.columnName===t.relation.columnName||o.databaseName===t.relation.columnName);n&&e.push(`column.${t.table}.${n.databaseName}`);}return e}applyNullableConstraint(t,e){return e===false?t.notNullable():e===true||this.sql.getDbType()==="mariadb"?t.nullable():t}executeBuilderMethod(t,e,r,n,o=true){let s;if(Array.isArray(r.type))s=e.enum(n[0],r.type);else if(typeof r.type=="string"&&Gr.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...n);else if(typeof r.type=="string")s=e.custom(n[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return o&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||qe(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),this.applyNullableConstraint(s,r.constraints?.nullable)),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(n=>{let o=this.executeBuilderMethod(t.table,n,t.column,e,false);return t.column.constraints?.default!==void 0&&o.default(t.column.constraints.default),this.applyNullableConstraint(o,t.column.constraints?.nullable),o});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,n=>{n.alterColumn(o=>{let s=this.executeBuilderMethod(t.table,o,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&!Rt(t.modelColumn,t.dbColumns.defaultValue)&&!_t(this.sql.getDbType(),t.modelColumn,t.dbColumns.defaultValue)&&s.default(null),this.applyNullableConstraint(s,t.modelColumn.constraints?.nullable),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),n=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),o=new ce(this.sql.getDbType());return o.createIndex(t.table,n,{constraintName:t.index}),o.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=C(t.relation.manyToManyOptions.throughModel),r=C(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let n=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,o=C(r);if(t.relation.type==="belongsTo"){let m=t.relation.model(),p=m.primaryKey,f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=H(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.model();if(typeof o=="string"&&o){let p=m.getColumns(),h=p.find(f=>f.columnName===o);if(h)o=h.databaseName;else {let f=m.primaryKey||"id",T=p.find(w=>w.columnName===f);if(T)o=T.databaseName;else {let w=m?.databaseCaseConvention||"preserve";o=H(o||f,w);}}}else {let p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=H(p,T);}}}let s=this.models.find(m=>m.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(m=>m.columnName===l);if(u)l=u.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=H(l,m);}if(t.relation.type==="belongsTo"){let m=a.find(p=>p.columnName===t.relation.foreignKey);if(m)l=m.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=H(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.manyToManyOptions.leftForeignKey,p=C(m),h=a.find(f=>f.columnName===p);if(h)l=h.databaseName;else {let f=s?.databaseCaseConvention||"preserve";l=H(p,f);}}let d=t.relation.onDelete?.toLowerCase(),c=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,m=>{let p=n||Z(t.table,l,e);m.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[o]},constraintName:p,onDelete:d,onUpdate:c});}).toQueries()}formatSqlStatements(t){return t.map(e=>({...e,sqlStatements:e.sqlStatements.map(r=>format(r,{...this.sql.inputDetails.queryFormatOptions}).replace(/\n/g," ").replace(/\s+/g," "))}))}};Gr.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var jt=Gr;var Zr=class Zr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],n=null,o={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==n&&(n=s.phase,e.length>0&&e.push(""),e.push(`// ${o[n]}`));let{up:a,down:l}=this.generateOperationCode(s);a&&e.push(...a),l&&r.push(...l);}return {up:e,down:r}}generateOperationCode(t){switch(t.type){case "CREATE_TABLE":return this.generateCreateTableCode(t);case "ADD_COLUMN":return this.generateAddColumnCode(t);case "MODIFY_COLUMN":return this.generateModifyColumnCode(t);case "DROP_COLUMN":return this.generateDropColumnCode(t);case "CREATE_INDEX":return this.generateCreateIndexCode(t);case "DROP_INDEX":return this.generateDropIndexCode(t);case "ADD_FOREIGN_KEY":return this.generateAddForeignKeyCode(t);case "DROP_FOREIGN_KEY":return this.generateDropForeignKeyCode(t);case "ADD_UNIQUE_CONSTRAINT":return this.generateAddUniqueCode(t);case "DROP_CONSTRAINT":return this.generateDropConstraintCode(t);case "ADD_CHECK_CONSTRAINT":return this.generateAddCheckCode(t);case "ADD_PRIMARY_KEY":return this.generateAddPrimaryKeyCode(t);case "DROP_TABLE":return this.generateDropTableCode(t);case "MODIFY_PRIMARY_KEY":return this.generateModifyPrimaryKeyCode(t);default:return {up:null,down:null}}}generateCreateTableCode(t){let e=t.data,r=[];r.push(`this.schema.createTable(${this.quote(e.table)}, (table) => {`);for(let o of e.columns){let s=this.generateColumnCode(e.table,o,true);r.push(` ${s}`);}r.push("});");let n=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:n}}generateAddColumnCode(t){let{table:e,column:r}=t.data,n=this.generateColumnCode(e,r,false),o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:o,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:n}=t.data,o=this.generateColumnCodeForModify(e,r,n),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(n.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],o=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:n,down:o}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u),s=o.length===1?this.quote(o[0]):`[${o.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.createIndex(${this.quote(e.table)}, ${s}, { constraintName: ${this.quote(e.index)} });`],l=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`];return {up:a,down:l}}generateDropIndexCode(t){let e=t.data,r=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`],n=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:n}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:n,referencedColumn:o,constraintName:s}=this.resolveRelationDetails(e),a=e.relation.onDelete?.toLowerCase(),l=e.relation.onUpdate?.toLowerCase(),u=[];s&&u.push(`constraintName: ${this.quote(s)}`),a&&u.push(`onDelete: ${this.quote(a)}`),l&&u.push(`onUpdate: ${this.quote(l)}`);let d=u.length>0?`, { ${u.join(", ")} }`:"",c=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(n)}, ${this.quote(o)}${d});`,"});"],m=s||Z(e.table,r,n),p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(m)});`,"});"];return {up:c,down:p}}generateDropForeignKeyCode(t){let e=t.constraint||t.data?.relation?.name;if(!e)return {up:null,down:null};let r=t.table||t.data?.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],o=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:n,down:o}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=`[${(e.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,n=t.constraint||e.name;if(!n||!r)return {up:null,down:null};if(e.type==="primary_key"){let a=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});"],l=[`// TODO: reverse primary key drop on ${this.quote(r)}`];return {up:a,down:l}}if(e.type==="unique"){let a=e.column,l=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(n)});`,"});"],u=[`// TODO: reverse unique constraint drop for ${this.quote(a)} on ${this.quote(r)}`];return {up:l,down:u}}if(e.expression!==void 0){let a=[`this.schema.dropCheck(${this.quote(r)}, ${this.quote(n)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:a,down:l}}let o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(n)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:o,down:s}}generateAddCheckCode(t){let e=t.data,r=[`this.schema.addCheck(${this.quote(e.table)}, ${this.quote(e.expression)}, { constraintName: ${this.quote(e.name)} });`],n=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:n}}generateAddPrimaryKeyCode(t){let e=t.data,o=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||qe(e.table,e.columns[0]),s=`[${e.columns.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.addConstraint("primary_key", { columns: ${s}, constraintName: ${this.quote(o)} });`,"});"],l=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`," table.dropPrimaryKey();","});"];return {up:a,down:l}}generateDropTableCode(t){let e=t.table||t.data?.table,r=[`this.schema.dropTable(${this.quote(e)});`],n=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:n}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],o=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:n,down:o}}generateColumnCode(t,e,r){let n=this.generateColumnTypeCode(e);if(!r)return n;if(e.isPrimary){let o=e.primaryKeyConstraintName||qe(t,e.columnName);n+=`.primaryKey({ constraintName: ${this.quote(o)} })`;}return e.unsigned&&(n+=".unsigned()"),e.zerofill&&(n+=".zerofill()"),e.constraints?.default!==void 0&&(n+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n+";"}generateColumnCodeForModify(t,e,r){let n=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?n+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&!Rt(e,r.defaultValue)&&!_t(this.sql.getDbType(),e,r.defaultValue)&&(n+=".default(null)"),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n}generateColumnTypeCode(t){let e=t.databaseName;if(Array.isArray(t.type)){let s=t.type.map(a=>this.quote(a)).join(", ");return `table.enum(${this.quote(e)}, [${s}])`}let r=t.type;if(new Set(["uuid","ulid","boolean","year","json","jsonb","binary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]).has(r))return `table.${r}(${this.quote(e)})`;if(r==="timestamp"||r==="datetime"){let s=[];return t.withTimezone&&s.push("withTimezone: true"),t.precision!=null&&s.push(`precision: ${t.precision}`),s.length>0?`table.${r}(${this.quote(e)}, { ${s.join(", ")} })`:`table.${r}(${this.quote(e)})`}return r==="date"||r==="time"?t.precision!=null?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="increment"||r==="bigIncrement"?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:r==="decimal"||r==="numeric"?t.precision!=null?t.scale!=null?`table.${r}(${this.quote(e)}, ${t.precision}, ${t.scale})`:`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="float"||r==="double"||r==="real"?t.precision!=null&&t.precision!==10?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="longtext"||r==="mediumtext"||r==="tinytext"?`table.${r}(${this.quote(e)})`:new Set(["varchar","char","string","integer","tinyint","smallint","mediumint","bigint","biginteger","varbinary"]).has(r)?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:Zr.BUILTIN_COLUMN_TYPES.has(r)?`table.${r}(${this.quote(e)})`:t.length!=null?`table.custom(${this.quote(e)}, ${this.quote(r)}, ${t.length})`:`table.custom(${this.quote(e)}, ${this.quote(r)})`}resolveRelationDetails(t){let e=t.table,r="id";if(t.relation.type==="belongsTo"){let l=t.relation.model();e=l.table;let u=l.primaryKey||"id";r=l.getColumns().find(m=>m.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=C(t.relation.manyToManyOptions.throughModel);let l=C(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let o=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=o.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=C(t.relation.manyToManyOptions.leftForeignKey);s=o.find(d=>d.columnName===l)?.databaseName||l;}else s=o.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName:C(t.relation.constraintName)||void 0;return {sourceColumn:s,referencedTable:e,referencedColumn:r,constraintName:a}}quote(t){return `"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}formatDefaultValue(t){return t==null?"null":t==="NULL"?'"NULL"':typeof t=="boolean"||typeof t=="number"?t.toString():t==="TRUE"||t==="true"?"true":t==="FALSE"||t==="false"?"false":this.quote(String(t))}};Zr.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var Yr=Zr;function Oh(i){return i.replace(/\s+/g," ").trim()}function Dh(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ah(i){let t=i.split(/\s+/).filter(n=>n.length>0),e=[],r=[];for(let n of t)n==="unsigned"||n==="zerofill"?e.push(n):r.push(n);return {bareBase:r.join(" "),modifiers:e}}function $h(i,t){return t.length===0?i:`${i} ${t.join(" ")}`}function Ue(i,t){let e=Oh(t.toLowerCase()),r=Dh(e);switch(i){case "sqlite":{let n=[{test:o=>o==="increment",normalized:"integer"},{test:o=>o==="bigincrement",normalized:"integer"},{test:o=>o.includes("int"),normalized:"integer"},{test:o=>o==="string",normalized:"varchar"},{test:o=>o.includes("char"),normalized:"varchar"},{test:o=>o.includes("text"),normalized:"text"},{test:o=>o.includes("clob"),normalized:"text"},{test:o=>o.includes("date"),normalized:"text"},{test:o=>o.includes("time"),normalized:"text"},{test:o=>o.includes("timestamp"),normalized:"text"},{test:o=>o.includes("datetime"),normalized:"text"},{test:o=>o.includes("blob"),normalized:"blob"},{test:o=>o.includes("real")||o.includes("floa")||o.includes("doub"),normalized:"real"},{test:o=>o.includes("numeric"),normalized:"numeric"},{test:o=>o.includes("bool"),normalized:"integer"},{test:o=>o.includes("uuid"),normalized:"varchar"},{test:o=>o.includes("ulid"),normalized:"varchar"},{test:o=>o.includes("jsonb"),normalized:"text"},{test:o=>o.includes("json"),normalized:"text"}];for(let o of n)if(o.test(r))return o.normalized;return r}case "mysql":case "mariadb":{let{bareBase:n,modifiers:o}=Ah(r),a=new Set(["int","integer","increment","tinyint","smallint","mediumint","bigint","bigincrement","float","double","double precision","real","decimal","numeric","year","bool","boolean"]).has(n);if(n.endsWith("text")||n==="text")return "text";let l;switch(n){case "int":case "integer":case "increment":l="integer";break;case "tinyint":l="boolean";break;case "smallint":l="smallint";break;case "mediumint":l="mediumint";break;case "bigint":case "bigincrement":l="bigint";break;case "float":l="float";break;case "double":case "double precision":l="double";break;case "real":l="double";break;case "decimal":case "numeric":l="numeric";break;case "string":case "varchar":case "character varying":l="varchar";break;case "char":case "character":l="char";break;case "uuid":l="varchar";break;case "ulid":l="varchar";break;case "date":l="date";break;case "datetime":l="datetime";break;case "timestamp":l="timestamp";break;case "time":l="time";break;case "year":l="year";break;case "jsonb":case "json":l=i==="mariadb"?"text":"json";break;case "enum":l="enum";break;case "binary":l="binary";break;case "varbinary":l="varbinary";break;case "tinyblob":l="tinyblob";break;case "mediumblob":l="mediumblob";break;case "longblob":l="longblob";break;case "blob":l="blob";break;case "boolean":case "bool":l="boolean";break;default:l=n;break}return a&&o.length>0?$h(l,o):l}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}default:return r}}var rt=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql._models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let n=await e.sql.getTableSchema(r.table),o={columns:r.getColumns().filter(f=>f?.type!==void 0&&f?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!n.columns.length){e.data.tablesToAdd.push({table:r.table,columns:o.columns});for(let w of o.indexes)n.indexes.map(q=>q.name).includes(w.name)||e.data.indexesToAdd.push({table:r.table,index:w.name});let f=r.getUniques?.()||[];for(let w of f)e.data.uniquesToAdd.push({table:r.table,name:w.name||"mandatory",columns:w.columns});let T=r.getChecks?.()||[];for(let w of T)e.data.checksToAdd.push({table:r.table,name:w.name,expression:w.expression});for(let w of o.relations){if(w.type!=="belongsTo")continue;let q=C(w.constraintName);n.foreignKeys.find(R=>R.name===q)||e.data.relationsToAdd.push({table:r.table,relation:w,onDelete:w.onDelete,onUpdate:w.onUpdate});}return}for(let f of o.columns)n.columns.some(w=>w.name===f.databaseName||w.name===f.columnName)||e.data.columnsToAdd.push({table:r.table,column:f});let s=r.getColumns();for(let f of n.columns)s.some(w=>w.databaseName===f.name||w.columnName===f.name)||e.data.columnsToDrop.push({table:r.table,column:f.name});for(let f of o.indexes)n.indexes.map(T=>T.name).includes(f.name)||e.data.indexesToAdd.push({table:r.table,index:f.name});let a=r.getUniques?.()||[];for(let f of a)n.indexes.some(w=>w.name===f.name&&w.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:f.name||"mandatory",columns:f.columns});let l=n.foreignKeys.map(f=>f.name);for(let f of n.indexes)f.isUnique||l.includes(f.name)||o.indexes.map(w=>w.name).includes(f.name)||e.data.indexesToDrop.push({table:r.table,index:f.name});for(let f of n.indexes){if(!f.isUnique||f.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(w=>w.name).includes(f.name)||e.data.uniquesToDrop.push({table:r.table,name:f.name});}let u=r.getChecks?.()||[];for(let f of u)n.checkConstraints.some(w=>w.name===f.name)||e.data.checksToAdd.push({table:r.table,name:f.name,expression:f.expression});let d=new Set(u.map(f=>f.name)),c=o.columns.filter(f=>Array.isArray(f.type)),m=new Set(c.map(f=>f.databaseName||f.columnName));for(let f of n.checkConstraints)if(!d.has(f.name)){let T=[...m].find(w=>{let q=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),D=new RegExp(`[\\["\\[]?${q}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i"),R=new RegExp(`[\\("\\[]?${q}[\\)"\\]]?(?:::text)?\\s*=\\s*ANY\\s*\\(`,"i");return D.test(f.expression)||R.test(f.expression)});if(T){let w=c.find(D=>(D.databaseName||D.columnName)===T),q=n.columns.find(D=>D.name===T);if(w&&q?.enumValues&&Array.isArray(w.type)){let D=[...w.type].sort(),R=[...q.enumValues].sort();if(!(D.length===R.length&&D.every((A,O)=>A===R[O]))){e.data.checksToDrop.push({table:r.table,name:f.name});let A=e.sql.getDbType(),O=A==="mssql"?"[":'"',K=A==="mssql"?"]":'"',le=w.type.map(v=>`'${v.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:f.name,expression:`${O}${T}${K} IN (${le})`});}}}else e.data.checksToDrop.push({table:r.table,name:f.name});}for(let f of o.columns){let T=n.columns.find(D=>D.name===f.databaseName||D.name===f.columnName);if(!T)continue;let w=!e.areColumnsEqual(T,f,n.indexes),q=e.getDefaultChange({table:r.table,dbColumns:T,modelColumn:f});(w||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:T,modelColumn:f});}for(let f of o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;if(f.type==="manyToMany"&&f.manyToManyOptions){let q=C(f.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:C(f.manyToManyOptions.leftForeignKey),foreignKey:f.manyToManyOptions.leftForeignKey,constraintName:f.constraintName?C(f.constraintName):Z(q,C(f.manyToManyOptions.leftForeignKey||Ll(r.table)),r.table),onDelete:f.onDelete,onUpdate:f.onUpdate},onDelete:f.onDelete,onUpdate:f.onUpdate});continue}let T=C(f.constraintName);if(T&&n.foreignKeys.some(q=>q.name===T))continue;n.foreignKeys.find(q=>e.relationMatchesDbRelation(r,f,q))||e.data.relationsToAdd.push({table:r.table,relation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let p=new Set(o.relations.filter(f=>f.type==="belongsTo").map(f=>{let T=C(f.foreignKey)||f.columnName,q=r.getColumns().find(D=>D.columnName===T)?.databaseName||T;return C(f.constraintName)||Z(r.table,q,f.model().table)}));for(let f of n.foreignKeys){if(f.name&&p.has(f.name))continue;o.relations.find(w=>w.type!=="belongsTo"&&w.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,w,f))||e.data.relationsToDrop.push({table:r.table,relation:f});}for(let f of o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;let T=n.foreignKeys.find(w=>e.relationMatchesDbRelation(r,f,w));T&&!e.areRelationsEqual(T,f)&&e.data.relationsToModify.push({table:r.table,dbRelation:T,modelRelation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let h=r.primaryKey;if(h&&!n.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[h]}),n.primaryKey&&!h&&e.data.primaryKeysToDrop.push({table:r.table,columns:n.primaryKey.columns,name:n.primaryKey.name}),h&&n.primaryKey){let f=r.getColumns().find(T=>T.columnName===h);f&&!e.arePrimaryKeysEqual(n.primaryKey,f)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:n.primaryKey,modelPrimaryKey:h});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let n=r.trim();return n?!this.emptyStatements.some(o=>o.test(n)):false})}getCodeStatements(){let e=new jt(this.sql).generateOperations(this.data);return new Yr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new jt(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),n={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let o of r)n[o.phase].push(...o.sqlStatements);return n}areColumnsEqual(t,e,r=[]){let n=t.name===e.databaseName,o=this.sql.getDbType(),s=Ue(o,t.dataType),a=typeof e.type=="string"?Ue(o,e.type):void 0,l=s.split(" ").filter(d=>d!=="unsigned"&&d!=="zerofill").join(" ");if(a&&n&&(n=l===a),Array.isArray(e.type)&&(o==="mysql"||o==="mariadb")){let d=[...e.type].sort(),c=t.enumValues?[...t.enumValues].sort():null;c&&n&&(n=d.length===c.length&&d.every((m,p)=>m===c[p]));}e.length!=null&&t.length!=null&&n&&(n=t.length===e.length);let u=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(o==="postgres"||o==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&n&&(n=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,c=t.isNullable;n=n&&d===c;}if(o==="mysql"||o==="mariadb"){if(e.unsigned!==void 0){let d=e.unsigned??false,c=t.unsigned??false;n&&(n=d===c);}if(e.zerofill!==void 0){let d=e.zerofill??false,c=t.zerofill??false;n&&(n=d===c);}}if(e.stringMode!==void 0){let d=e.stringMode??false,c=t.stringMode??false;n&&(n=d===c);}return n}areRelationsEqual(t,e){let r=C(e.constraintName),n=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",c=u.getColumns().find(h=>h.columnName===d),m=u.table,p=c?.databaseName||d;n=n&&t.referencedTable===m&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=C(e.manyToManyOptions.throughModel);n=n&&t.referencedTable===u;}let o=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&n&&(n=o===a),l&&n&&(n=s===l),n}relationMatchesDbRelation(t,e,r){let n,o=e;if(o&&o.model){if(typeof o.model=="function"&&o.model.table)n=o.model;else if(typeof o.model=="function")try{let f=o.model();f&&f.table&&(n=f);}catch{}}if(!n)return false;let s=e.type==="belongsTo"?n.table:e.type==="manyToMany"&&e.manyToManyOptions?C(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=C(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),d=(o.type||"belongsTo")==="belongsTo"?C(o.foreignKey):o.columnName,c=l.find(f=>f.columnName===d);c&&(d=c.databaseName);let m=n.primaryKey||"id",h=n.getColumns().find(f=>f.columnName===m)?.databaseName||m;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let n=t.columns[0]===e.databaseName,o=this.sql.getDbType();if(["mysql","mariadb"].includes(o))return n;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return n&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Ue(e,t.dbColumns.dataType),n=typeof t.modelColumn.type=="string"?Ue(e,t.modelColumn.type):void 0;if(n&&r!==n||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(n==="timestamp"||n==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0;if(s&&!a)return "set";if(!s&&a){let l=t.dbColumns.defaultValue;return _t(e,t.modelColumn,l)||Rt(t.modelColumn,l)||t.modelColumn.type==="uuid"&&Ef(e,l)?false:"drop"}if(s&&a){let l=String(t.dbColumns.defaultValue),u=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,l),c=this.normalizeDefaultValue(e,n||r,u);return d!==c?"set":false}return false}normalizeDefaultValue(t,e,r){let n=String(r).trim();if(!n)return n;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=n.match(/^'(.*)'$/s);if(s&&(n=s[1]),n==="{}"||n==="")return "{}";let a=JSON.parse(n);return JSON.stringify(a)}catch{}n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),/^true$/i.test(n)?"true":/^false$/i.test(n)?"false":/^null$/i.test(n)?"null":(n)}if(t==="mysql"||t==="mariadb"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);if(o&&(n=o[1]),/^current_timestamp(?:\(\d+\))?$/i.test(n))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(n))return "true";if(/^0$/.test(n))return "false"}return n}if(t==="sqlite"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),n.toLowerCase()}return n}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let n of r){if(n.type!=="manyToMany"||!n.manyToManyOptions||n.manyToManyOptions.wasModelProvided)continue;let o=C(n.manyToManyOptions.throughModel);if(t.has(o))continue;t.add(o);let s=this.models.find(v=>v.table===n?.manyToManyOptions?.primaryModel),a=n.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find(v=>v.columnName===l),c=a.getColumns().find(v=>v.columnName===u);if(!d||!c)continue;let m=C(n.manyToManyOptions.leftForeignKey)||l,p=C(n.manyToManyOptions.rightForeignKey)||u,h=await this.sql.getTableSchema(o);if(!h.columns.length){this.data.tablesToAdd.push({table:o,columns:[this.clonePkAsColumn(d,m),this.clonePkAsColumn(c,p)]}),this.pushM2mFkRelations({throughTable:o,leftModel:s,rightModel:a,leftFkName:m,rightFkName:p,onDelete:n.onDelete,onUpdate:n.onUpdate,constraintName:void 0});continue}let f=this.clonePkAsColumn(d,m),T=this.clonePkAsColumn(c,p),w=h.columns.find(v=>v.name===m),q=h.columns.find(v=>v.name===p),D=w?this.areColumnsEqual(w,f,h.indexes):false,R=q?this.areColumnsEqual(q,T,h.indexes):false;for(let v of h.foreignKeys){let ne=v.referencedTable===s.table,Ye=v.referencedTable===a.table;if(!ne&&!Ye)continue;let _e=ne?m:p,Me=v.columns[0];Me&&Me!==_e&&(this.data.relationsToDrop.push({table:o,relation:v}),Me!==m&&Me!==p&&this.data.columnsToDrop.push({table:o,column:Me}));}let $={};D||($[f.databaseName]=f),R||($[T.databaseName]=$[T.databaseName]||T);for(let v of Object.keys($))this.data.columnsToAdd.push({table:o,column:$[v]});let A=this.buildBelongsToRelation(o,()=>s,m,l,void 0,n.onDelete,n.onUpdate),O=this.buildBelongsToRelation(o,n.model,p,u,void 0,n.onDelete,n.onUpdate),K=h.foreignKeys.find(v=>v.referencedTable===s.table&&v.columns.length===1&&v.columns[0]===m),le=h.foreignKeys.find(v=>v.referencedTable===a.table&&v.columns.length===1&&v.columns[0]===p);if(!K){let v=h.foreignKeys.find(ne=>ne.referencedTable===s.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(A);}if(!le){let v=h.foreignKeys.find(ne=>ne.referencedTable===a.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(O);}}}}async removeFkChurnByName(){let t=new Set;for(let n of this.data.relationsToAdd)t.add(n.table);for(let n of this.data.relationsToDrop)t.add(n.table);let e=new Map;for(let n of t){let o=await this.sql.getTableSchema(n),s=new Set((o.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(n,s);}let r=new Map;for(let n of this.models){let o=n.getRelations(),s=new Set;for(let a of o){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=n.getColumns().find(m=>m.columnName===l)?.databaseName||l,c=C(a.constraintName)||Z(n.table,d,a.model().table);s.add(c);}r.set(n.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async n=>{let o=await this.sql.getTableSchema(n.table),s=this.models.find(f=>f.table===n.table),a=s?.getColumns()||[],l=n.relation.columnName;n.relation.type==="belongsTo"?l=a.find(T=>T.columnName===n.relation.foreignKey)?.databaseName||n.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let u=n.table,d=n.relation.foreignKey;if(n.relation.type==="belongsTo"){let f=n.relation.model();u=f.table;let T=f.primaryKey||"id";d=f.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let c=new Set([l,n.relation.columnName].filter(Boolean)),m=o.foreignKeys.some(f=>{if(f.columns.length!==1||f.referencedColumns.length!==1)return false;let T=c.has(f.columns[0]),w=f.referencedTable===u,q=f.referencedColumns[0]===d;return T&&w&&q}),p=C(n.relation.constraintName)||Z(n.table,l,u),h=e.get(n.table)||new Set;if(m||p&&h.has(p))return null;if(n.relation.type==="manyToMany"&&n.relation.manyToManyOptions){let f=C(n.relation.manyToManyOptions.throughModel),T=C(n.relation.manyToManyOptions.leftForeignKey),w=C(n.relation.manyToManyOptions.rightForeignKey),q=n.table===f&&n.relation.columnName===T&&n.relation.model().table===s?.table,D=n.table===f&&n.relation.columnName===w&&n.relation.model().table!==s?.table,R=await this.sql.getTableSchema(f),$=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===T&&O.referencedTable===(s?.table||"")),A=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===w&&O.referencedTable===n.relation.model().table);if(q&&$||D&&A)return null}return n})).then(n=>n.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async n=>{let o=this.models.find(u=>u.table===n.table);if(!o)return n;let s=o.getRelations(),a=o.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let c=a.find(T=>T.columnName===u.foreignKey)?.databaseName||u.foreignKey,m=u.model(),p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p)?.databaseName||p;return n.relation.columns.length===1&&n.relation.columns[0]===c&&n.relation.referencedTable===m.table&&n.relation.referencedColumns.length===1&&n.relation.referencedColumns[0]===f})?null:n})).then(n=>n.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,n,o,s,a){let l=o?C(o):Z(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var Ve=class{};Ve.modelCaseConvention="camel",Ve.databaseCaseConvention="snake";var Bf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");return o+=n.final("hex"),`${r.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},kf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=String(t).trim(),[n,o]=r.split(":");if(!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=n.toLowerCase(),a=o.toLowerCase(),l=Pe.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),u=l.update(a,"hex","utf8");return u+=l.final("utf8"),u}catch(e){throw new S("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Kf=(i,t)=>{try{let e=Pe.randomBytes(32),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");o+=n.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Qf=(i,t)=>{try{let e=String(t).trim(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=privateDecrypt(i,Buffer.from(n,"hex")),a=Pe.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(o,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new S("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var z=class{static defineMetadata(t,e,r,n){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let o=this.store.get(r);o||(o=new Map,this.store.set(r,o));let s=o.get(n);s||(s=new Map,o.set(n,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let n=e;for(;n;){let o=this.store.get(n);if(o){let s=o.get(r);if(s&&s.has(t))return s.get(t)}n=Object.getPrototypeOf(n);}}};z.store=new WeakMap;var Vl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ul=Vl.length,Ph=10,Eh=16,Bh=(i,t)=>{let e="";for(let r=0;r<t;r++){let n=i%Ul;e=Vl.charAt(n)+e,i=(i-n)/Ul;}return e},kh=i=>{let t=ie().crypto.randomBytes(i),e="";for(let r=0;r<i;r++){let n=t[r];e+=Vl.charAt(n%Ul);}return e},Lf=()=>{let i=Math.floor(Date.now()/1e3),t=Bh(i,Ph),e=kh(Eh);return t+e};var Xr=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var en=class extends Oe{constructor(e,r,n){super(e,r);this.type="hasMany";this.foreignKey=n,this.type="hasMany";}};var tn=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var rn=class extends Oe{constructor(e,r,n){super(e,r);this.type="manyToMany";this.primaryModel=n.primaryModel,this.relatedModel=e.table,this.throughModel=n.throughModel,this.leftForeignKey=n.leftForeignKey,this.rightForeignKey=n.rightForeignKey;}};function _(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let n=e.constructor;if(t){if(z.getMetadata(Ct,e))throw new S("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");z.defineMetadata(Ct,r,e),z.defineMetadata(Ct,r,e.constructor);}let o=i.databaseName??H(r,n.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??qe(n.table,r),autoUpdate:i.autoUpdate,autoCreate:i.autoCreate,databaseName:o,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,unsigned:i.unsigned,zerofill:i.zerofill,stringMode:i.stringMode,expression:i.expression,constraints:{nullable:i.nullable,default:i.default}};s.validate=i.validate;let a=z.getMetadata(jr,e)||[];a.push(s),z.defineMetadata(jr,a,e);}}_.primary=Kh;_.date=tg;_.datetime=rg;_.timestamp=ng;_.time=og;_.boolean=eg;_.json=sg;_.uuid=Fh;_.ulid=Uh;_.integer=Lh;_.bigInteger=Hh;_.float=Qh;_.decimal=zh;_.increment=Wh;_.bigIncrement=jh;_.string=Vh;_.text=Jh;_.binary=Gh;_.enum=Yh;_.encryption={symmetric:Zh,asymmetric:Xh};_.computed=ig;function Kh(i={}){return _({...i,primaryKey:true})}function Qh(i={}){return _({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?Number.parseInt(t):Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function Lh(i={}){return _({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function Wh(i={}){return _({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function jh(i={}){return _({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function Fh(i={}){return _({type:"uuid",...i,prepare:t=>t||ie().crypto.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function Uh(i={}){return _({type:"ulid",...i,prepare:t=>t||Lf(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Vh(i={}){return _({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Jh(i={}){return _({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Hh(i={}){return _({type:"bigint",...i,serialize:t=>{if(t!==void 0){if(t===null)return null;if(typeof t=="number")return t;if(typeof t=="string")return Number.parseInt(t);if(typeof t=="bigint")return Number(t)}},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function zh(i={}){return _({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function Gh(i={}){return _({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Yh(i,t={}){return _({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Zh(i){return _({...i,prepare:t=>t&&Bf(i.key,t),serialize:t=>t&&kf(i.key,t)})}function Xh(i){return _({...i,prepare:t=>t&&Kf(i.publicKey,t),serialize:t=>t&&Qf(i.privateKey,t)})}function eg(i={}){return _({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function tg(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"DATE_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"date",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"DATE_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...o.openApi||{}}})}function rg(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"ISO",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"datetime",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"ISO",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function ng(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"TIMESTAMP",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"timestamp",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"TIMESTAMP",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function og(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"TIME_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"time",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"TIME_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},stringMode:t,openApi:{type:"string",format:"time",description:"HH:mm:ss",...o.openApi||{}}})}function sg(i={}){return _({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function ig(i,t={}){return _({...t,expression:i})}function Wf(i){try{return z.getMetadata(jr,i.prototype)||[]}catch{return []}}function jf(i){return z.getMetadata(Ql,i.prototype)||[]}function Ff(i){return (z.getMetadata(Ql,i.prototype)||[]).map(e=>{let{type:r,model:n,columnName:o,foreignKey:s}=e,a=C(s),l=n();switch(r){case "belongsTo":return new Xr(l,o,a);case "hasOne":return new tn(l,o,a);case "hasMany":return new en(l,o,a);case "manyToMany":if(!e.manyToManyOptions)throw new S("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=n();return new rn(u,o,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:C(e.manyToManyOptions.throughModel),leftForeignKey:C(e.manyToManyOptions.leftForeignKey),rightForeignKey:C(e.manyToManyOptions.rightForeignKey)});default:throw new S("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Uf(i){return z.getMetadata(Ct,i)||z.getMetadata(Ct,i.prototype)}function Vf(i){return z.getMetadata(Mf,i.prototype)||[]}function Jf(i){return z.getMetadata(xf,i.prototype)||[]}function Hf(i){return z.getMetadata(Of,i.prototype)||[]}var ye=class{};ye.columns=new WeakMap,ye.byName=new WeakMap,ye.byDatabaseName=new WeakMap;var Ae=class extends Ve{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");if(t&&"value"in t)return t.value;throw new Error(`Table name not set for model "${this.name}". Use defineModel() to create models.`)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Uf(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=ye.columns.get(this);return t||(t=Wf(this),ye.columns.set(this,t)),t}static getColumnsByName(){let t=ye.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),ye.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=ye.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),ye.byDatabaseName.set(this,t)),t}static getRelations(){return jf(this)}static getIndexes(){return Vf(this)}static getUniques(){return Jf(this)}static getChecks(){return Hf(this)}static async validate(t){var s,a;let e=this.getColumns(),r={},n=this.primaryKey,o=n&&t?.[n]!==void 0?"update":"insert";for(let l of e){if(l.expression)continue;let u=l.validate;if(!u)continue;let d=t?t[l.columnName]:void 0,c=Array.isArray(u)?u:[u];for(let m of c)try{let p=await m(d,{model:this,column:l.columnName,operation:o,data:t});if(!(p&&p.valid)){let h=p&&p.message||"Validation failed";(r[s=l.columnName]||(r[s]=[])).push(h);}}catch{(r[a=l.columnName]||(r[a]=[])).push("Validation error");}}if(Object.keys(r).length>0)throw new Pt(r);return {valid:true}}};Ae.zodEngine=null,Ae.softDeleteColumn="deletedAt",Ae.softDeleteValue=bt();var Mt=class extends N{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var U=class extends N{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var re=class extends N{constructor(e,r=[],n,o=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=n,this.disableReturning=o;}};var Ce=class extends N{constructor(e,r,n,o="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=n,this.mode=o,this.returning=s;}};var xt=class extends N{constructor(e=[],r="inserted"){super("returning");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="returning";this.file="returning";this.columns=e,this.prefix=r;}};var Ee=class extends N{constructor(e,r=[],n=[],o=false){super("update",o);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=n;}};var M=class extends N{constructor(e,r,n=false,o,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=n,this.operator=o,this.value=s;}};var $e=class extends N{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var j=class extends M{constructor(e,r,n=false,o,s,a=false,l,u){super(e,r,n,"=",s,a);this.file="where_json";this.jsonOperator=o,this.value=s,this.path=l,this.comparisonOperator=u;}};var Re=class extends N{constructor(e,r,n,o="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=n,this.chainsWith=` ${o}`;}};var zf;zf=Symbol.toStringTag;var G=class{constructor(t,e,r,n){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=n;this[zf]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}toSql(){return this.toSqlFn()}unWrap(){return this.unWrapFn()}};var ag=(i,t,e,r,n,o=false)=>{let s=Object.create(t.prototype);for(let a of Object.keys(i)){let l=i[a],u=e.get(a),d=a;u||(u=r.get(a),u&&(d=u.columnName));let c=u!==void 0,m=o?true:n?n.has(d):true;if(c){if(!m)continue;if(l===null){s[d]=null;continue}if(u?.serialize){let p=u.serialize(l);if(p!==null&&typeof p?.then=="function")throw new Error(`hysteria-orm: column "${d}" on model "${t.name}" has an async serialize function, but serializers must be synchronous. Move async work to prepare or a getter.`);s[d]=p;continue}s[d]=l;continue}(!o||n&&n.has(d))&&(s[d]=l);}if(n)for(let a of n)a in s||(s[a]=null);return s},he=(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),n=t.getColumnsByDatabaseName(),o=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let p=u.match(/\s+as\s+(.+)$/i);p&&s.push(p[1].trim());continue}let c=u;if(c.includes(".")&&(c=c.split(".").pop()),c==="*")continue;let m=r.get(c)?.columnName??c;s.push(m);}let a=s.length?new Set(s):null,l=i.map(u=>ag(u,t,r,n,a,o));return l.length===1?l[0]:l};var Ft=class{constructor(t){this.observers=t??[];}add(t){this.observers.push(t);}async notifyBefore(t){for(let e of this.observers)e?.onBeforeQuery&&await e.onBeforeQuery(t);}async notifyAfter(t,e){for(let r of this.observers)r?.onAfterQuery&&(t.result??(t.result=e),await r.onAfterQuery(t));}async notifyError(t){for(let e of this.observers)e?.onQueryError&&await e.onQueryError(t);}},Gf=i=>{if(!i)return "OTHER";let t=i.trim().toUpperCase();return t.startsWith("SELECT")?"SELECT":t.startsWith("INSERT")?"INSERT":t.startsWith("UPDATE")?"UPDATE":t.startsWith("DELETE")?"DELETE":"OTHER"};var nn=ie();function Jl(i){let t=nn.timing.now()-i;return Math.round(t*100)/100}var J=async(i,t,e,r,n="rows",o)=>{await e.ensureConnected();let s={id:nn.crypto.randomUUID(),sql:i,params:t,model:void 0,operation:Gf(i),timestamp:nn.timing.now()};try{let u=e.observerChain;u&&typeof u.notifyBefore=="function"&&await u.notifyBefore(s);}catch{}let a=nn.timing.now(),l=u=>{o?.shouldNotLog||ct(i,e.logs,t,e.inputDetails.queryFormatOptions,r,u);};try{let u=e.driverAdapter;if(!u)throw new S("ExecSql","CONNECTION_NOT_ESTABLISHED");let d=o?.timeout,c=d?new AbortController:void 0,m,p=lg(()=>u.execute(i,t,{returning:n,sqlLiteOptions:o?.sqlLiteOptions,signal:c?.signal,connection:e.sqlConnection}),e.inputDetails.connectionPolicies?.retry,e.logs),h;try{d&&c?(h=await Promise.race([p,new Promise((f,T)=>{m=setTimeout(()=>{let w=new S("ExecSql::timeout","QUERY_TIMEOUT",new Error(`Query exceeded the ${d.ms}ms timeout`));d.cancel&&c.abort(w),T(w);},d.ms);})]),p.catch(()=>{})):h=await p;}finally{m&&clearTimeout(m);}try{let f=Jl(a),T=e.observerChain;if(T&&typeof T.notifyAfter=="function"){let w={...s,duration:f,result:h};await T.notifyAfter(w);}}catch{}return l(Jl(a)),u.extract(h,n)}catch(u){throw l(Jl(a)),u}},on=async(i,t,e,r={},n)=>{let o=e.driverAdapter;if(!o)throw new S("ExecSqlStreaming","CONNECTION_NOT_ESTABLISHED");return await o.stream(i,t,{...r,connection:e.sqlConnection??void 0},{onData:n.onData})};async function lg(i,t={maxRetries:0,delay:0},e=false){let r=0,n=t.maxRetries||0,o=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<n)return r++,Nu(`Retrying sql in ${o}ms (attempt ${r}/${n})`,"info",e),await new Promise(l=>setTimeout(l,o)),s();throw a}}return s()}var Y=class extends N{constructor(e,r,n,o,s){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=n,this.isRawValue=o??false,this.distinct=s;}};var Ut=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Ff(t),this.modelRelationsMap=new Map(this.modelRelations.map(n=>[n.columnName,n]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new S("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function sn(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}var Ot=i=>typeof i=="number"?i:parseFloat(i);var X=class extends N{constructor(e,r,n=false,o,s,a=false,l,u){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=` ${r}`,this.isNegated=n,this.operator=o,this.value=s,this.subquery=l,this.group=u;}};var an=class extends N{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var ln=class extends N{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Je=class extends N{constructor(e,r,n,o="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=n,this.jsonOperator=o,this.isRawValue=s;}};var se=class extends N{constructor(e,r,n,o="inner",s,a=false,l){super(`${o} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=n,this.type=o,this.on=s,this.additionalConditions=l;}};var Vt=class extends N{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var un=class extends N{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var dn=class extends N{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Jt=class extends N{constructor(e,r="asc",n=false){super("order by",n);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var mn=class mn{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs,typeof t.getColumns=="function"?(this.modelColumns=t.getColumns(),this.modelColumnsMap=t.getColumnsByName?.()??new Map(this.modelColumns.map(r=>[r.columnName,r]))):(this.modelColumns=[],this.modelColumnsMap=mn.EMPTY_MAP);}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new Vt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Vt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Jt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Jt(t,"asc",true)),this}limit(t){return typeof t!="number"&&g.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new un(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new dn(t),this}};mn.EMPTY_MAP=new Map;var cn=mn;var nt=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",false,n,o)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",false,n,o)),this}whereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}andWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}orWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",true,n,o)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new M(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new M(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new M(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new M(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new M(t,"and",false,"in",e)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",false,"in",e)),this):(this.whereNodes.push(new M("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"and",true,"in",e)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",true,"in",e)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new M(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new M(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new M(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new M(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new $e(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new $e(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new M(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new M(t,"or",true,"=",e??[],true)),this}};var pn=class extends cn{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}crossJoin(t,e){let r=typeof t=="string"?t:t.table;return this.joinNodes.push(new se(e?`${r} as ${e}`:r,"","","cross",{operator:"="})),this}using(...t){let e=this.joinNodes[this.joinNodes.length-1];if(!e||!t.length||e.isRawValue||e.type==="cross"||e.type==="natural")throw new S("JoinQueryBuilder::using","USING_REQUIRES_JOIN");return e.using=t.map(r=>String(r)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,n,o){if(e===void 0)return this.join(typeof t=="string"?t:t.table);let s=r,a=n,l=typeof n=="function"?n:o;if(!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","inner",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","left",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","right",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,n,o){let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var fn=class extends pn{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[a,l]=r;this.modelSelectedColumns.push(l);let u=this.resolveComputedColumn(a);if(u){this.selectNodes.push(new Y(`(${u.expression}) as ${l}`,void 0,void 0,true));return}let d=H(a,this.model.databaseCaseConvention);this.selectNodes.push(new Y(d,l));return}let n=r;this.modelSelectedColumns.push(n);let o=this.resolveComputedColumn(n);if(o){this.selectNodes.push(new Y(`(${o.expression}) as ${o.alias}`,void 0,void 0,true));return}let s=H(n,this.model.databaseCaseConvention);this.selectNodes.push(new Y(s));}),this}selectRaw(e){return this.selectNodes.push(new Y(e,void 0,void 0,true)),this}selectFunc(e,r,n){return this.selectNodes.push(new Y(r,n,e)),this}countDistinct(e,r){return this.selectNodes.push(new Y(e,r,"count",false,true)),this}sumDistinct(e,r){return this.selectNodes.push(new Y(e,r,"sum",false,true)),this}avgDistinct(e,r){return this.selectNodes.push(new Y(e,r,"avg",false,true)),this}rank(e,r={}){return this.pushWindow("rank",e,r)}denseRank(e,r={}){return this.pushWindow("dense_rank",e,r)}rowNumber(e,r={}){return this.pushWindow("row_number",e,r)}pushWindow(e,r,n){return this.selectNodes.push(new Y(new Fr(e,Df(n.partitionBy),Af(n.orderBy)),r)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}resolveComputedColumn(e){let r=this.model.getColumnsByName?.();if(!r||r.size===0)return;let n=e.includes(".")?e.split(".").pop():e,o=r.get(n);if(o?.expression)return {expression:o.expression,alias:o.databaseName||n}}clearFrom(){return this.fromNode=new U(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}table(e){return this.fromNode=new U(e),this}distinct(){return this.distinctNode=new an,this}distinctOn(...e){return this.distinctOnNode=new ln(e),this}selectJson(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract")),this}selectJsonText(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract_text")),this}selectJsonArrayLength(e,r,n){return this.selectNodes.push(new Je(e,r,n,"array_length")),this}selectJsonKeys(e,r,n){return this.selectNodes.push(new Je(e,r,n,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Je(e,"",r,"raw",true)),this}};var yn=class extends fn{constructor(e,r,n=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=n;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,n){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&n===void 0?this.andWhereSubQuery(e,"in",r):r instanceof B&&n===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function")?this.andWhereSubQuery(e,r,n):this.andWhere(e,r,n)}andWhere(e,r,n){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",false,o,s)),this}orWhere(e,r,n){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",false,o,s)),this}whereColumn(e,r,n){return this.andWhereColumn(e,r,n)}andWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"and",false,o,new x(s))),this}orWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"or",false,o,new x(s))),this}whereNotColumn(e,r,n){return this.andWhereNotColumn(e,r,n)}andWhereNotColumn(e,r,n){return this.pushNotColumnWhere("and",e,r,n)}orWhereNotColumn(e,r,n){return this.pushNotColumnWhere("or",e,r,n)}pushNotColumnWhere(e,r,n,o){let s="!=",a=false,l;return o!==void 0?(s=n,l=o,a=true):l=n,this.whereNodes.push(new M(r,e,a,s,new x(l))),this}whereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}andWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}orWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",true,o,s)),this}whereBetween(e,r,n){return this.andWhereBetween(e,r,n)}andWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"and",false,"between",[r,n])),this}orWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"or",false,"between",[r,n])),this}whereNotBetween(e,r,n){return this.andWhereNotBetween(e,r,n)}andWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"and",true,"between",[r,n])),this}orWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"or",true,"between",[r,n])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"and",false,"in",r)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",false,"in",r)),this):(this.whereNodes.push(new M("false","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"in",r)}whereNotIn(e,r){return this.andWhereNotIn(e,r)}andWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"and",true,"in",r)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",true,"in",r)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new M(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new M(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new M(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new M(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"and",false,n?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"or",false,n?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"or",true,n?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"or",false,"=",r,true)),this}having(e,r,n){return this.andHaving(e,r,n)}andHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"and",false,o,s)),this}orHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"or",false,o,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new X(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new X(e,"or",false,"=",[],true)),this}havingNull(e){return this.andHavingNull(e)}andHavingNull(e){return this.havingNodes.push(new X(e,"and",false,"is null",void 0)),this}orHavingNull(e){return this.havingNodes.push(new X(e,"or",false,"is null",void 0)),this}havingNotNull(e){return this.andHavingNotNull(e)}andHavingNotNull(e){return this.havingNodes.push(new X(e,"and",false,"is not null",void 0)),this}orHavingNotNull(e){return this.havingNodes.push(new X(e,"or",false,"is not null",void 0)),this}havingIn(e,r){return this.andHavingIn(e,r)}andHavingIn(e,r){return this.pushHavingIn("and",e,r,false)}orHavingIn(e,r){return this.pushHavingIn("or",e,r,false)}havingNotIn(e,r){return this.andHavingNotIn(e,r)}andHavingNotIn(e,r){return this.pushHavingIn("and",e,r,true)}orHavingNotIn(e,r){return this.pushHavingIn("or",e,r,true)}havingBetween(e,r){return this.andHavingBetween(e,r)}andHavingBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"between",r)),this}orHavingBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"between",r)),this}havingNotBetween(e,r){return this.andHavingNotBetween(e,r)}andHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"not between",r)),this}orHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"not between",r)),this}havingExists(e){return this.andHavingExists(e)}andHavingExists(e){return this.pushHavingExists("and",e,false)}orHavingExists(e){return this.pushHavingExists("or",e,false)}havingNotExists(e){return this.andHavingNotExists(e)}andHavingNotExists(e){return this.pushHavingExists("and",e,true)}orHavingNotExists(e){return this.pushHavingExists("or",e,true)}havingWrapped(e){return this.andHavingWrapped(e)}andHavingWrapped(e){return this.pushHavingGroup("and",e)}orHavingWrapped(e){return this.pushHavingGroup("or",e)}pushHavingIn(e,r,n,o){let s=o?"not in":"in";if(Array.isArray(n))return this.havingNodes.push(new X(r,e,false,s,n)),this;let a=this.buildSubQuery(n);return this.havingNodes.push(new X(r,e,false,s,[],false,a.extractQueryNodes())),this}pushHavingExists(e,r,n){let o=r instanceof B?r:new B(this.model,this.sqlDataSource);return o.isNestedCondition=true,typeof r=="function"&&r(o),this.havingNodes.push(new X("",e,false,n?"not exists":"exists",[],false,o.extractQueryNodes())),this}pushHavingGroup(e,r){let n=new B(this.model,this.sqlDataSource);return n.isNestedCondition=true,r(n),this.havingNodes.push(new X("",e,false,"=",[],false,void 0,n.havingNodes)),this}buildSubQuery(e){if(e instanceof B)return e;let r=new B(this.model,this.sqlDataSource),n=e(r);return n!=null&&"extractQueryNodes"in n?n:r}andWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"and");return this.whereNodes.push(n),this}orWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"or");return this.whereNodes.push(n),this}};var hn=class extends yn{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"or",false,"raw",e)),this}whereJsonObject(t,e){return this.andWhereJsonObject(t,e)}andWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"and",false,"=",e)),this}orWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"or",false,"=",e)),this}whereNotJsonObject(t,e){return this.andWhereNotJsonObject(t,e)}andWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"and",true,"=",e)),this}orWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"or",true,"=",e)),this}whereJsonPath(t,e,r,n){return this.andWhereJsonPath(t,e,r,n)}andWhereJsonPath(t,e,r,n){return this.pushJsonPath("and",t,e,r,n,false),this}orWhereJsonPath(t,e,r,n){return this.pushJsonPath("or",t,e,r,n,false),this}whereJsonSupersetOf(t,e){return this.andWhereJsonSupersetOf(t,e)}andWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotSupersetOf(t,e){return this.andWhereJsonNotSupersetOf(t,e)}andWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"contains",e)),this}orWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"contains",e)),this}whereJsonSubsetOf(t,e){return this.andWhereJsonSubsetOf(t,e)}andWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"subset",e)),this}orWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"subset",e)),this}whereJsonNotSubsetOf(t,e){return this.andWhereJsonNotSubsetOf(t,e)}andWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"subset",e)),this}orWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"subset",e)),this}whereJsonHasNone(t,e){return this.andWhereJsonHasNone(t,e)}andWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"and",false,"has none",e)),this}orWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"or",false,"has none",e)),this}pushJsonPath(t,e,r,n,o,s){let a=new j(e,t,s,"path",o,false,r,n);this.whereNodes.push(a);}};var B=class i extends hn{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.returningNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.comments=[],this.hints=[],this.astParser=new b(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new y(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,n]=e;if(typeof r=="function"){let o=new i(this.model,this.sqlDataSource),s=r(o),a=s!=null&&"extractQueryNodes"in s?s:o;return this.selectNodes.push(new Y(a.extractQueryNodes(),n)),this}return this.selectNodes.push(new Y(r.extractQueryNodes(),n)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",n=>J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(n=>n[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new S("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:n}=this.unWrap();return this.execSqlWithSlaveHandling("read",async o=>await on(r,n,o,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;r+=n.length,yield n;}}async paginateWithCursor(e,r){if(!this.orderByNodes.length)throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_REQUIRED");let n=this.orderByNodes;if(n.some(m=>m.isRawValue))throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_RAW_NOT_SUPPORTED");let o=n.map(m=>m.column),s=n[0].direction==="desc"?"<":">";if(r){let m=Array.isArray(r.value)?r.value:[r.value];this.andWhere(p=>{for(let h=0;h<o.length;h++){let f=h;p.orWhere(T=>{for(let w=0;w<f;w++)T.where(o[w],"=",m[w]);T.where(o[f],s,m[f]);});}});}this.limit(e+1);let a=await this.many(),l=a.length>e,u=l?a.slice(0,e):a,d=u[u.length-1],c=o.map(m=>m.includes(".")?m.slice(m.lastIndexOf(".")+1):m);return {data:u,hasMore:l,nextCursor:d?{key:c.length===1?c[0]:c,value:c.length===1?d[c[0]]:c.map(m=>d[m])}:null}}lockForUpdate(e={}){return this.lockQueryNodes.push(new Xe("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Xe("for_share",e.skipLocked,e.noWait)),this}forNoKeyUpdate(e={}){return this.assertPgLockStrength("forNoKeyUpdate","FOR NO KEY UPDATE"),this.lockQueryNodes.push(new Xe("for_no_key_update",e.skipLocked,e.noWait)),this}forKeyShare(e={}){return this.assertPgLockStrength("forKeyShare","FOR KEY SHARE"),this.lockQueryNodes.push(new Xe("for_key_share",e.skipLocked,e.noWait)),this}assertPgLockStrength(e,r){if(this.dbType!=="postgres")throw new S(`QueryBuilder::${e}`,`LOCK_STRENGTH_NOT_SUPPORTED_IN_${this.dbType.toUpperCase()}`,new Error(`${r} is only supported by postgres`))}timeout(e,r={}){return this.queryTimeout={ms:e,cancel:r.cancel??false},this}comment(e){return this.assertValidSqlComment(e),this.comments.push(e),this}hintComment(e){this.assertValidSqlComment(e);let r=e.slice(3,-2).trim(),n=this.hints[0];return this.hints=[n?`${n.slice(0,-2).trimEnd()} ${r} */`:`/*+ ${r} */`],this}clearComment(){return this.comments=[],this}clearHintComment(){return this.hints=[],this}assertValidSqlComment(e){let r=()=>{throw new S("QueryBuilder::comment","INVALID_SQL_COMMENT")};(!e.trim().length||e.includes("?"))&&r();let n=(this.dbType==="mysql"||this.dbType==="mariadb")&&e.startsWith("#");if(e.startsWith("--")||n){/[\r\n]/.test(e)&&r();return}if(e.startsWith("/*")&&e.endsWith("*/")&&e.length>=4){let o=e.slice(2,-2);(o.includes("/*")||o.includes("*/"))&&r();return}r();}union(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e,true)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n,true)),this}intersect(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"intersect")),this}except(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"except")),this}resolveSetOperationNodes(e){return typeof e=="string"?e:(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes()}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.buildCountQuery(e);let r=await this.one();return r?Ot(r.total):0}needsDerivedTableCount(){return this.groupByNodes.length>0||this.havingNodes.length>0||this.distinctNode!==null||this.distinctOnNode!==null}buildCountQuery(e="*"){if(!this.needsDerivedTableCount()){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);return}this.clearOrderBy(),this.clearLimit(),this.clearOffset();let r=this.extractQueryNodes();this.withNodes=[],this.distinctNode=null,this.distinctOnNode=null,this.clearSelect(),this.fromNode=new U(r,"g"),this.joinNodes=[],this.whereNodes=[],this.groupByNodes=[],this.havingNodes=[],this.lockQueryNodes=[],this.unionNodes=[],this.comments=[],this.hints=[],this.selectRaw(`count(${e}) as total`);}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?Ot(r.total):0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?Ot(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?Ot(r.total):0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?Ot(r.total):0}async columnInfo(e){let r=typeof this.fromNode.table=="string"?this.fromNode.table:this.model.table,o=await(await this.getSqlDataSource("read")).getTableInfo(r);return e===void 0?o:o.find(s=>s.name===e)}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new S("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let n=new i(this.model,this.sqlDataSource),o=e(n),a=(o!=null&&"extractQueryNodes"in o?o:n).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}withSchema(e){return this.schemaName=e,this}fromRaw(e,r=[]){return this.fromNode=new U(new x(e,r)),this}with(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("materialized",e,s.extractQueryNodes())),this}withNotMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withNotMaterialized","NOT_MATERIALIZED_CTE_NOT_SUPPORTED",new Error("NOT MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("not materialized",e,s.extractQueryNodes())),this}insert(e,r){let n=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,[this.interpreterUtils.stripComputedFromData(n)],r,o),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),l=Object.fromEntries(s.map((p,h)=>[p,a[h]]));this.insertNode=new re(this.fromNode,[l],r,o);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!o)return Array.isArray(m)&&m.length?m[0]:m})}insertMany(e,r){let n=e.map(s=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(s).map(a=>[a,s[a]])))),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,n,r,o),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return o?void 0:[];let s=await Promise.all(e.map(async c=>{let{columns:m,values:p}=this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert",this.dbType);return Object.fromEntries(m.map((h,f)=>[h,p[f]]))}));this.insertNode=new re(this.fromNode,s,r,o);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await J(a,l,u,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!o)return d})}upsert(e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(Object.keys(e)),s=Object.keys(r),a=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(e).map(l=>[l,e[l]])));return this.insertNode=new re(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),d=Object.fromEntries(l.map((f,T)=>[f,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,o,n,[e]);let{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),[d],void 0,true),new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning)]),p=await this.getSqlDataSource("write"),h=await J(c,m,p,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(h)?h:[h]})}upsertMany(e,r,n,o={updateOnConflict:true}){let s=this.interpreterUtils.filterComputedColumns(r),a=n.map(l=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(l).map(u=>[u,l[u]]))));return this.insertNode=new re(new U(this.model.table),a,void 0,true),this.onDuplicateNode=new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let l=[];if(await Promise.all(n.map(async p=>{let{columns:h,values:f}=this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert",this.dbType),T=Object.fromEntries(h.map((w,q)=>[w,f[q]]));l.push(T);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(l,e,s,o,n);let{sql:u,bindings:d}=this.astParser.parse([new re(new U(this.model.table),l,void 0,true),new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,n,o,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=K=>this.interpreterUtils.formatStringColumn("mssql",K),d=[],c=e.map(K=>`select ${a.map(v=>(d.push(K[v]),`@${d.length}`)).join(", ")}`),m=a.map(u).join(", "),p=c.join(" union all "),h=r.map(K=>`target.${u(K)} = source.${u(K)}`).join(" and "),f=n.filter(K=>!r.includes(K)).map(K=>`target.${u(K)} = source.${u(K)}`).join(", "),T=a.map(u).join(", "),w=a.map(K=>`source.${u(K)}`).join(", "),q=o.returning&&o.returning.length?o.returning.map(K=>`inserted.${u(K)}`).join(", "):a.map(K=>`inserted.${u(K)}`).join(", "),R=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",$=`merge into ${l} as target using (${p}) as source (${m}) on ${h} ${R} when not matched then insert (${T}) values (${w}) output ${q};`,A=await this.getSqlDataSource("write"),O=await J($,d,A,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(O)?O:[O]}update(e,r){let n=this.interpreterUtils.stripComputedFromData(e),o=Object.keys(n),s=Object.values(n);this.updateNode=new Ee(this.fromNode,o,s),this.returningNode=this.buildReturningNode("update",r);let a=this.returningNode!==null;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(o,s,"update",this.dbType);this.updateNode=new Ee(this.fromNode,l,u);let{sql:d,bindings:c}=this.astParser.parse(this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes])),m=await this.getSqlDataSource("write");return J(d,c,m,this.dbType,a?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:a?"fetch":"affectedRows"}})})}buildReturningNode(e,r){return !r?.length||!this.interpreterUtils.dialectEmitsReturning(this.dbType)?null:new xt(r,e==="delete"?"deleted":"inserted")}withReturningNode(e){if(!this.returningNode)return e;if(this.dbType==="mssql"){let[r,...n]=e;return [r,this.returningNode,...n]}return [...e,this.returningNode]}truncate(){return this.truncateNode=new qt(this.fromNode),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),n=await this.getSqlDataSource("write");await J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout});})}delete(e){this.deleteNode=new Mt(this.fromNode),this.returningNode=this.buildReturningNode("delete",e);let r=this.returningNode!==null;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:n,bindings:o}=this.astParser.parse(this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes])),s=await this.getSqlDataSource("write");return J(n,o,s,this.dbType,r?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:n=bt()}=e||{};return this.updateNode=new Ee(this.fromNode,[r],[n]),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:o,values:s}=this.interpreterUtils.prepareColumns([r],[n],"update",this.dbType);this.updateNode=new Ee(this.fromNode,o,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return J(a,l,u,this.dbType,"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return it(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),n=lt(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${n}`:n,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new Y("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes());return {sql:this.withQuery?`${this.withQuery} ${e}`:e,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=W(this.modelSelectedColumns),e.distinctNode=W(this.distinctNode),e.distinctOnNode=W(this.distinctOnNode),e.selectNodes=W(this.selectNodes),e.withQuery=W(this.withQuery),e.joinNodes=W(this.joinNodes),e.whereNodes=W(this.whereNodes),e.groupByNodes=W(this.groupByNodes),e.havingNodes=W(this.havingNodes),e.orderByNodes=W(this.orderByNodes),e.lockQueryNodes=W(this.lockQueryNodes),e.unionNodes=W(this.unionNodes),e.withNodes=W(this.withNodes),e.comments=[...this.comments],e.hints=[...this.hints],e.schemaName=this.schemaName,e.fromNode=W(this.fromNode),e.limitNode=W(this.limitNode),e.offsetNode=W(this.offsetNode),e.returningNode=W(this.returningNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){if(this.selectNodes.length||(this.selectNodes=[new Y("*")]),this.schemaName){this.fromNode&&typeof this.fromNode.table=="string"&&(this.fromNode.schema=this.schemaName);for(let n of this.joinNodes)n.schema=this.schemaName;}if(this.insertNode)return [this.insertNode,this.onDuplicateNode].filter(Boolean);if(this.updateNode)return this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.deleteNode)return this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.truncateNode)return [this.truncateNode];let e=this.comments.map(n=>new Lt(n)),r=this.hints.length?[new Lt(this.hints.join(" "),true)]:[];return [...this.withNodes,...e,this.distinctNode,this.distinctOnNode,...this.selectNodes,...r,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let n=await e(),o=await r();return [n,o]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let n=await this.getSqlDataSource(e);if(!(n!==this.sqlDataSource))return r(n);try{return await r(n)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:n.host,port:n.port,username:n.username,password:n.password,database:n.database,type:n.getDbType()}),await r(this.sqlDataSource);throw a}}};function Yf(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:ug(i)}function ug(i){let{parentCount:t,relationType:e,hasLimitOffset:r}=i;return r&&(e==="hasMany"||e==="manyToMany")?"batched":t===1?"join":e==="manyToMany"?typeof t=="number"&&t<=10?"join":"batched":typeof t=="number"&&t<10?"join":"batched"}var Hl=ie(),ot=class i extends B{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Ut(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[n,o]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(n,o.columnName);}expandModelSelectColumns(){let e=this.selectNodes;if(!e.length){if(this.joinNodes.length)return;for(let[,r]of this.modelColumnsMap)r.expression||e.push(new Y(r.databaseName,r.columnName));return}for(let r of e){if(r.isRawValue||r.alias!==void 0||typeof r.column!="string"||r.column.includes(".")||r.column==="*")continue;let n=this.modelColumnsMap.get(r.column);!n||n.expression||(r.alias=n.columnName);}}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(e){let r=await this.one();if(!r)throw new S(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(){await this.model.beforeFetch?.(this),this.expandModelSelectColumns();let r=await super.many();if(!r.length)return [];let n=he(r,this.model,this.modelSelectedColumns);if(!n)return [];let o=Array.isArray(n)?n:[n];return this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(o),o}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;yield n,r+=n.length;}}async stream(e={}){await this.model.beforeFetch?.(this),this.expandModelSelectColumns();let{sql:r,bindings:n}=this.unWrap(),o=await this.getSqlDataSource("read");return await on(r,n,o,e,{onData:async(a,l)=>{let u=he([l],this.model,this.modelSelectedColumns);u&&(this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}async paginateWithCursor(e,r){return super.paginateWithCursor(e,r)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{returning:r.returning})}upsert(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return o.upsertMany(s,a,[l],{updateOnConflict:n.updateOnConflict??true,returning:n.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=r.length>0?Object.keys(r[0]):[];return o.upsertMany(e,s,r,{updateOnConflict:n.updateOnConflict??true,returning:n.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource.getTransactionBoundSqlDataSource()??this.sqlDataSource;return new st(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,n){return this.getModelManager(n?.trx).updateRecord(e,r,n)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let n=this.model.primaryKey;if(!n)throw new S(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let o=e[n],s=o?{[n]:o}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,n){let{column:o=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[o]:s};return this.getModelManager(n?.trx).updateRecord(e,a,{returning:n?.returning})}async firstOrInsert(e,r,n){let o=this.getModelManager(n?.trx),s=await o.findOne({where:e});if(s)return s;let a={...e,...r};return o.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,n,o,s={}){if(Array.isArray(n)||(n=[n]),!n.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new S(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=H(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=H(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=n.map((p,h)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...o?o(p,h):{}}));class c extends Ae{static get table(){return a.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await new st(c,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let n=r.returning,o=super.update(e,n);return new G(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>{if(!n||!this.returningNode)return o;let s=await o;return he(s,this.model,n)})}softDelete(e={}){let r=super.softDelete(e);return new G(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>r)}delete(e={}){let r=e.returning,n=super.delete(r);return new G(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>{if(!r||!this.returningNode)return n;let o=await n;return he(o,this.model,r)})}async getCount(e="*"){this.buildCountQuery(e);let r=await this.one();return r?+r.total:0}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?+r.total:0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?+r.total:0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?+r.total:0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?+r.total:0}async paginate(e,r){let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof B)&&typeof e[1]=="string"){let[r,n]=e;return super.select(r,n),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,n){let o,s={strategy:"auto"};typeof r=="function"?(o=r,n&&(s=n)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,o?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,n){return this.andHavingRelated(e,r,n)}andHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.whereExists(d),this}orHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.orWhereExists(d),this}notHavingRelated(e,r,n){return this.andNotHavingRelated(e,r,n)}andNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.whereNotExists(d),this}orNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=W(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let n=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,n);}));}async processRelationsWithStrategy(e){let r=e.length,n=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),o=async s=>{let a=Yf({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of n)await o(s);return}await Promise.all(n.map(o));}async loadRelationViaJoin(e,r){let n=e.relation,o=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,n,o).many();this.mapJoinedResultsToModels(a,r,n,o);}buildJoinQuery(e,r,n){let o=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)o.selectNodes.push(W(s));else for(let[s,a]of this.model.getColumnsByDatabaseName())a.expression||o.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=W(s);this.qualifyWhereNodeColumns(a,this.model.table),o.whereNodes.push(a);}for(let s of this.groupByNodes)o.groupByNodes.push(W(s));for(let s of this.orderByNodes)o.orderByNodes.push(W(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(o.limitNode=W(this.limitNode)),this.offsetNode&&(o.offsetNode=W(this.offsetNode))),r.type){case "hasOne":case "hasMany":o.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":o.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;o.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),o.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(o,r,e,n);for(let s of e.whereNodes)o.whereNodes.push(W(s));for(let s of e.orderByNodes)o.orderByNodes.push(W(s));return o}selectRelationColumnsWithAlias(e,r,n,o){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=n.selectNodes.filter(m=>typeof m.column=="string"),c=d.some(m=>m.column==="*"||m.column.endsWith(".*"));if(d.length===0||c)for(let[m,p]of u)e.selectRaw(`${a.table}.${m} as ${s}${o}${p.columnName}`);else for(let m of d){let p=m.column,h=p.includes(".")?p.split(".").pop():p,f=u.get(h)||l.get(h),T=f?.databaseName??h,w=m.alias??f?.columnName??h;e.selectRaw(`${a.table}.${T} as ${s}${o}${w}`);}}mapJoinedResultsToModels(e,r,n,o){let{columnName:s,type:a}=n,l=n.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];u.has(c)||u.set(c,[]);let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.get(c).push(m));}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||[];});}else {let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];if(!u.has(c)){let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.set(c,m));}}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||null;});}}extractRelationDataFromRow(e,r,n){let o=`${r}${n}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(o)){let d=u.substring(o.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof M)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Re)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof $e)for(let n of e.nodes)this.qualifyWhereNodeColumns(n,r);}serializeRelationData(e,r){for(let n of Object.keys(e)){let o=r.get(n);o?.serialize&&e[n]!==null&&e[n]!==void 0&&(e[n]=o.serialize(e[n]));}}async loadRelationViaBatch(e,r){let n=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,n);}mapRelatedModelsToModels(e,r,n){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let o=new Map;n.forEach(m=>{let p=m[e.foreignKey];p&&o.set(String(p),m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=null;return}let h=o.get(String(p));m[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;n.forEach(m=>{if(!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=m[e.model.primaryKey];p&&s.set(String(p),m);}),r.forEach(m=>{let p=m[e.foreignKey];if(!p){m[e.columnName]=null;return}let h=s.get(String(p));m[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;n.forEach(m=>{let p=m[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=a.get(String(p))||[];m[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,c=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||H(d,this.model.modelCaseConvention);n.forEach(m=>{let p=m[c];if(p==null)return;let h=String(p);u.has(h)||u.set(h,[]),delete m[c],u.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=u.get(String(p))||[];m[e.columnName]=h;});break;default:throw new S(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,n){return this.getRelatedModelsQueryForRelation(e,r,n).many()}getRelatedModelsQueryForRelation(e,r,n){let o=this.getFilterValuesFromModelsForRelation(r,n);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,o);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,o);let l=Qe(Hl.crypto.randomBytes(6)),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(O=>O.isRawValue?O.column:`${this.interpreterUtils.formatStringColumn(this.dbType,O.column)} ${O.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let c=e.with(u,O=>O.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,o));s&&c.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&c.whereRaw(`rn_${l} > ${a}`);let m=e.modelSelectedColumns.map(O=>fo(O,u,e.model.table));return c.select(...m).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!n.length)return e;let h=e.limitNode?.limit,f=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(O=>O.includes(".")?O:`${r.model.table}.${O}`):[`${r.model.table}.*`];if(!h&&!f)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o);let w=Qe(Hl.crypto.randomBytes(6)),q=`${r.model.table}_cte_${w}`,D=e.orderByNodes.map(O=>{if(O.isRawValue)return O.column;let K=O.column.includes(".")?O.column:`${r.model.table}.${O.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,K)} ${O.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Qe(Hl.crypto.randomBytes(6))}_left_foreign_key`,$=e.with(q,O=>O.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,R]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${D}) as rn_${w}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o));h&&$.whereRaw(`rn_${w} <= ${h+(f||0)}`),f&&$.whereRaw(`rn_${w} > ${f}`);let A=T.map(O=>fo(O,q,e.model.table));return $.select(...A).select([`${q}.${R}`,p.leftForeignKey]).table(q);default:throw new S(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);case "belongsTo":return r.map(n=>n[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);default:throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,n,o){let s=new y(r.model),a=new y(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new S(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new S(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===u.throughModel&&p.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let c=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${c} = ${m}`),n&&typeof o=="number"&&e.groupByRaw(c).andHavingRaw(`count(*) ${n} ${o}`);return}default:throw new S(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}};function Zf(){return {}}var st=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Zf(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,n])=>{e.orderBy(r,n);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many()}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,offset:t.offset});if(e===null)throw t.customError?t.customError:new S(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new S(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one()}insert(t,e={}){let r=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(t).map(u=>[u,t[u]]))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),[r],e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new G(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(q){throw q}let{columns:u,values:d}=this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert",this.sqlType),c={};u.forEach((q,D)=>{let R=d[D];c[q]=R,t[q]??(t[q]=R);});let m=!e.returning||e.returning.length===0,{sql:p,bindings:h}=this.astParser.parse([new re(new U(this.model.table),[c],e.returning,m)]),f=await J(p,h,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(m)return;if(this.sqlType==="mysql")return this.handleMysqlInsert(f,[t],"one",e.returning);let T=f[0];return T?he([T],this.model,e.returning):t})}insertMany(t,e={}){let r=t.map(u=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(u).map(d=>[d,u[d]])))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),r,e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new G(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}let u=t.map(T=>{let{columns:w,values:q}=this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert",this.sqlType),D={};return w.forEach((R,$)=>{let A=q[$];D[R]=A,T[R]??(T[R]=A);}),D}),d=!e.returning||e.returning.length===0,{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),u,e.returning,d)]),p=await J(c,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let h=p;return h.length?he(h,this.model,e.returning)||[]:[]})}upsertMany(t,e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(e),s=r.map(p=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(p).map(h=>[h,p[h]])))),a=new re(new U(this.model.table),s,void 0,true),l=n.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0;new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",l);let d=()=>{let p=this.astParser.parse([a]);return {sql:p.sql,bindings:p.bindings}},c=()=>{let p=this.astParser.parse([a]);return {sql:lt(this.sqlDataSource,p.sql),bindings:p.bindings}},m=()=>{let{sql:p,bindings:h}=c();return it(p,h)};return new G(d,c,m,async()=>{let p=r.map(A=>{let{columns:O,values:K}=this.interpreterUtils.prepareColumns(Object.keys(A),Object.values(A),"insert",this.sqlType);return Object.fromEntries(O.map((le,v)=>[le,K[v]]))});if(this.sqlType==="mssql")return this.executeMssqlMerge(p,t,o,n,r);let h=!n.returning||n.returning.length===0,f=!h&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0,{sql:T,bindings:w}=this.astParser.parse([new re(new U(this.model.table),p,void 0,true),new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",f)]),q=await J(T,w,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(h)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(q.length<r.length&&!(n.updateOnConflict??true)){let K=t[0],le=r.map(ne=>ne[K]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(K,le).many()}return he(q,this.model,n.returning)||[]}let D=t[0],R=r.map(A=>A[D]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(D,R).many()})}async executeMssqlMerge(t,e,r,n,o){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=A=>this.interpreterUtils.formatStringColumn("mssql",A),u=[],d=t.map(A=>`select ${s.map(K=>(u.push(A[K]),`@${u.length}`)).join(", ")}`),c=s.map(l).join(", "),m=d.join(" union all "),p=e.map(A=>`target.${l(A)} = source.${l(A)}`).join(" and "),h=r.filter(A=>!e.includes(A)).map(A=>`target.${l(A)} = source.${l(A)}`).join(", "),f=s.map(l).join(", "),T=s.map(A=>`source.${l(A)}`).join(", "),w=n.returning&&n.returning.length?n.returning.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "):s.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "),D=(n.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",R=`merge into ${a} as target using (${m}) as source (${c}) on ${p} ${D} when not matched then insert (${f}) values (${T}) output ${w};`,$=await J(R,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});if($.length===0&&!(n.updateOnConflict??true)){let A=e[0],O=o.map(le=>le[A]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(A,O).many()}return $}async updateRecord(t,e,r){let n=new Set(this.model.getColumns().map(w=>w.columnName)),o=Object.keys(e).filter(w=>n.has(w)),s=o.map(w=>e[w]),{columns:a,values:l}=this.interpreterUtils.prepareColumns(o,s,"update",this.sqlType),{primaryKey:u}=this.model;if(!u)throw new S(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let c=r?.returning??[],m=c.length>0&&!this.interpreterUtils.hasComputedColumn(c)&&this.interpreterUtils.shouldFetchNatively(this.sqlType,"update"),{sql:p,bindings:h}=this.astParser.parse([new Ee(new U(this.model.table),a,l),new M(u,"and",false,"=",t),...m?[new xt(c)]:[]]),f=await J(p,h,this.sqlDataSource,this.sqlType,m?"rows":"affectedRows",m?{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}:void 0);if(!c.length)return;if(m){if(!f.length)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return he([f[0]],this.model,c)}let T=await this.findOneByPrimaryKey(t,r?.returning);if(!T)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return T}async deleteRecord(t){if(!this.model.primaryKey)throw new S(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new M(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:n}=this.astParser.parse([new Mt(new U(this.model.table)),e]);await J(r,n,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new ot(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,n){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?he([a],this.model):null}return he(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...n??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let o=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...n||["*"]).whereIn(this.model.primaryKey,o).many();return r==="one"?s.length?s[0]:null:s}handleWhereCondition(t,e,r=false){if(e)for(let[n,o]of Object.entries(e))n==="$and"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{for(let l of o)this.handleWhereCondition(a,l,false);}):n==="$or"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of o)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,n,o,r);}applyFieldCondition(t,e,r,n=false){if(r==null||typeof r!="object"){r===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",r):t.where(e,"=",r);return}let o=r,s=o.op,a=o.value;switch(s){case "$eq":a===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?n?t.orWhereNotNull(e):t.whereNotNull(e):n?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":n?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":n?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":n?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":n?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;n?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;n?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":n?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":n?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":n?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":n?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":n?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":n?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":n?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":n?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":n?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":n?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:n?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var zl=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??bt()});Dt();var be=class{constructor(t){this.options=t;}static async createDriver(t){throw new S("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};ue();var Ht=class Ht extends be{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new Ht(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new L("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new L("mongodb");return new Ht(this.mongoClient)}};Ht.mongoClient=null;var gn=Ht;ue();var zt=class zt extends be{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new zt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new L("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new L("mssql");return new zt(this.mssqlClient)}};zt.mssqlClient=null;var bn=zt;ue();var Gt=class Gt extends be{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Gt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new L("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new L("mysql2");return new Gt(this.mysqlClient)}};Gt.mysqlClient=null;var Tn=Gt;ue();var Yt=class Yt extends be{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Yt(this.pgClient);let e=await import('pg').catch(()=>{throw new L("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new L("pg");return new Yt(this.pgClient)}};Yt.pgClient=null;var wn=Yt;ue();var Zt=class Zt extends be{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Zt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new L("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new L("sqlite3");return new Zt(this.sqlite3Client)}};Zt.sqlite3Client=null;var Sn=Zt;var me=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Tn.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await wn.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Sn.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await gn.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await bn.createDriver(),this.mssqlDriver;default:throw new S(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;default:return null}}};me.mysqlDriver=null,me.pgDriver=null,me.sqliteDriver=null,me.mssqlDriver=null,me.mongodbDriver=null;Dt();ue();var Nn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.coerceNumericTypes&&!e.driverOptions?.types?{getTypeParser:(o,s)=>{let a=!s||s==="text";return a&&o===20?l=>BigInt(l):a&&o===1700?l=>Number.parseFloat(l):r.types.getTypeParser(o,s)}}:void 0;this.pool=new r.Pool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions,...n?{types:n}:{}});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.connect()}releaseConnection(t){t?.release();}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION"),e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`);}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=0,o=t.replace(/\?/g,()=>`$${++n}`);if(!r.signal)return (r.connection??this.pool).query(o,e);let s=r.connection??await this.pool.connect(),a=!r.connection,l=()=>{let u=s.processID;u!=null&&this.pool.query("SELECT pg_cancel_backend($1)",[u]).catch(()=>{});};r.signal.addEventListener("abort",l,{once:true});try{return await s.query(o,e)}finally{r.signal.removeEventListener("abort",l),a&&s.release();}}extract(t,e){return e==="rows"?t.rows:e==="raw"?t:t.rowCount}async stream(t,e,r,n){let o=r.connection,s=!o,a=o??await this.pool.connect(),l=await import('pg-query-stream').catch(()=>{throw new L("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,c=t.replace(/\?/g,()=>`$${++d}`),m=new l.default(c,e,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(m),h=0,f=false,T=false,w=q=>{if(s)try{a.release(q);}catch{}};return p.on("data",q=>{if(n.onData){h++,Promise.resolve(n.onData(u,q)).then(()=>{h--,f&&h===0&&!T&&(w(),u.end());}).catch(D=>{T=true,w(D),u.destroy(D);});return}u.write(q);}),p.on("end",()=>{f=true,h===0&&!T&&(w(),u.end());}),p.on("error",q=>{T=true,w(q),u.destroy(q);}),u}};var qn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=r.createPool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.getConnection()}releaseConnection(t){t?.release();}async beginTransaction(t,e){e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`),await t.beginTransaction();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){if(!r.signal)return (r.connection??this.pool).query(t,e);let n=r.connection??await this.pool.getConnection(),o=!r.connection,s=()=>{let a=n.threadId;a!=null&&this.pool.query(`KILL QUERY ${Number(a)}`).catch(()=>{});};r.signal.addEventListener("abort",s,{once:true});try{return await n.query(t,e)}finally{r.signal.removeEventListener("abort",s),o&&n.release();}}extract(t,e){let r=t;return e==="affectedRows"?r[0]?.affectedRows??0:e==="raw"?t:r[0]}async stream(t,e,r,n){let o=this.pool,s=r.connection??await o.getConnection(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=s.connection.query(t,e).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),d=0,c=false,m=false,p=()=>{try{s.release();}catch{}};return u.on("data",h=>{if(n.onData){d++,Promise.resolve(n.onData(a,h)).then(()=>{d--,c&&d===0&&!m&&(p(),a.end());}).catch(f=>{m=true,p(),a.destroy(f);});return}a.write(h);}),u.on("end",()=>{c=true,d===0&&!m&&(p(),a.end());}),u.on("error",h=>{m=true,p(),a.destroy(h);}),a.on("close",()=>{p();}),a}};var Cn=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=new r.Database(String(e.database??":memory:"),e.driverOptions?.mode??void 0,n=>{if(n)throw new S("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});}createPool(){}async closePool(){await new Promise((t,e)=>{this.pool.close(r=>{r&&e(r),t();});});}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){return await this.promisify(t,e,r)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.pool;return new Gl(o,t,e,{onData:n.onData})}promisify(t,e,r){let n=r.sqlLiteOptions??{},o=n.mode||"fetch",s=n.customConnection??r.connection??this.pool;if(["begin","begin transaction","commit","rollback"].includes(t.trim().toLowerCase()))return new Promise((u,d)=>{s.run(t,e,function(c){c&&d(c),u(this.changes);});});if(o==="fetch")return new Promise((u,d)=>{s.all(t,e,(c,m)=>{c&&d(c),u(m||[]);});});if(!n?.typeofModel)return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});});if(o==="insertOne"||o==="insertMany"){let u=`${t} returning *`;return new Promise((d,c)=>{s.all(u,e,(m,p)=>{if(m)return c(m);d(p||[]);});})}return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});})}},Gl=class extends Readable{constructor(t,e,r=[],n){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=n;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(n,o)=>{if(n){r=true,this.emit("error",n);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,o)).then(()=>{if(!r){if(s){this.push(a);return}this.push(o);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},n=>{if(n){r=true,this.emit("error",n);return}e=true,t===0&&!r&&this.push(null);});}};ue();var Rn=class{constructor(t,e,r){this.dialect="mssql";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.driverOptions,{options:o,...s}=n??{};this.pool=new r.ConnectionPool({server:e.host??"localhost",port:e.port,database:e.database,user:e.username,password:e.password,...s,options:{trustServerCertificate:E.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...o,abortTransactionOnError:false,enableImplicitTransactions:false}});}async createPool(){await this.pool.connect();}async closePool(){await this.pool.close();}async reserveConnection(){return this.pool.transaction()}releaseConnection(){}async beginTransaction(t,e){if(e.isolationLevel){let r=await this.getMssqlTransactionLevel(e.isolationLevel);await t.begin(r);return}await t.begin();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){let n=this.pool,o=r.connection?r.connection.request():n.request();e.forEach((l,u)=>{o.input(`p${u}`,l);});let s=0,a=t.replace(/\?|@(\d+)/g,()=>`@p${s++}`);if(r.signal){let l=()=>{try{o.cancel();}catch{}};r.signal.addEventListener("abort",l,{once:true});try{return await o.query(a)}finally{r.signal.removeEventListener("abort",l);}}return o.query(a)}extract(t,e){return e==="affectedRows"?t.rowsAffected[0]:e==="raw"?t:t.recordset}async stream(t,e,r,n){let o=r.connection??this.pool,s=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),a=o.request();a.stream=true,e.forEach((p,h)=>{a.input(`p${h}`,p);});let l=0,u=t.replace(/\?|@(\d+)/g,()=>`@p${l++}`),d=0,c=false,m=false;return a.on("row",p=>{if(!m){if(n.onData){d++,Promise.resolve(n.onData(s,p)).then(()=>{d--,c&&d===0&&!m&&s.end();}).catch(h=>{m=true,s.destroy(h);});return}s.write(p);}}),a.on("error",p=>{m=true,s.destroy(p);}),a.on("done",()=>{c=true,d===0&&!m&&s.end();}),a.query(u),s}async getMssqlTransactionLevel(t){let e=await import('mssql').then(r=>r.default.ISOLATION_LEVEL).catch(r=>{throw g.error(r),new L("mssql")});switch(t){case "READ UNCOMMITTED":return e.READ_UNCOMMITTED;case "READ COMMITTED":return e.READ_COMMITTED;case "REPEATABLE READ":return e.REPEATABLE_READ;case "SERIALIZABLE":return e.SERIALIZABLE;default:throw new S("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${t}`)}}};var yg=()=>{ge({name:"pg",dialects:["postgres","cockroachdb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Nn(i,t,e)}}),ge({name:"mysql2",dialects:["mysql","mariadb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new qn(i,t,e)}}),ge({name:"sqlite3",dialects:["sqlite"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Cn(i,t,e)}}),ge({name:"mssql",dialects:["mssql"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Rn(i,t,e)}});};yg();var Sg=async i=>{if(i==="bun"){await(await Promise.resolve().then(()=>(ay(),iy))).registerBunDrivers();return}if(i==="web"){(await Promise.resolve().then(()=>(tu(),eu))).registerWebDrivers();return}if(i==="react-native"){await(await Promise.resolve().then(()=>(tu(),eu))).registerReactNativeDrivers();return}},Dn=async(i,t)=>{let e=ur(t?.jsEnvironment);await Sg(e);let r=await ey(i,e,t?.driver,t);return await r.createPool(),r};var er=class er{constructor(){}static run(t,e){return er.storage.run(t,e)}static getTransaction(){return er.storage.getStore()}};er.storage=new AsyncLocalStorage;var He=er;var tr=class i{constructor(t,e,r=false,n=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Qe(ie().crypto.randomBytes(16)),this.isolationLevel=e,this.isNested=r,this.nestingDepth=n;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await He.run(e,()=>t(e));return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){if(this.getIsolationLevelQuery(),this.isNested){let r=this.getSavePointName();this.sql.type==="mssql"?await this.sql.rawQuery(`SAVE TRANSACTION ${r}`):await this.sql.rawQuery(`SAVEPOINT ${r}`),this.isActive=true;return}(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("BEGIN TRANSACTION",this.sql.logs);let t=this.sql.driverAdapter,e=this.sql.sqlConnection;if(!t||!e)throw new S("TRANSACTION::transaction","CONNECTION_NOT_ESTABLISHED");await t.beginTransaction(e,{isolationLevel:this.isolationLevel,rawQuery:(r,n)=>this.sql.rawQuery(r,n??[])}),this.isActive=true;}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("COMMIT",this.sql.logs),e&&r&&await e.commitTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new S("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("ROLLBACK",this.sql.logs),e&&r&&await e.rollbackTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async releaseConnection(){if(this.connectionReleased)return;let t=null;try{this.sql.driverAdapter?.releaseConnection(this.sql.sqlConnection);}catch(e){t=e,g.error(e);}this.sql.sqlConnection=null;try{await this.sql.disconnect();}catch(e){g.warn(`Transaction::releaseConnection - disconnect failed: ${e?.message??e}`);}if(this.connectionReleased=true,t)throw t}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new S("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new S("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}};var ru=Symbol.for("hysteria.orm.SqlDataSource"),my,py,Be=class i extends(py=kt,my=ru,py){constructor(e){super(e);this[my]=true;this.globalTransaction=null;this.globalTransactionLock=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.lockConnection=null;this.lockKeyToId=new Map;this.driverAdapter=null;this.id=ie().crypto.randomUUID();this.logicalSourceId=ie().crypto.randomUUID();this.cacheAdapter=new hr;this.migrationConfig={path:E.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.zodEngine=null;this.lazyLoad=false;this.connecting=null;this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:vt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(n=>new i(n)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure,this.lazyLoad=e?.lazyLoad??false,this.clsEnabled=e?.clsEnabled??true;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&ru in e&&e[ru]===true}get isClsEnabled(){return this.clsEnabled}getOnSlaveServerFailure(){return this.onSlaveServerFailure}addObserver(e){return this.observerChain||(this.observerChain=new Ft([])),this.observerChain.add(e),this}static async useConnection(e,r){let n=new i(e);await n.connect();try{await r(n),n.isConnected&&await n.disconnect();}catch(o){throw n.isConnected&&await n.disconnect(),o}}async connect(){if(this.isConnected)throw new S("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");try{this.driverAdapter=await Dn(this.sqlType,this.inputDetails),this.sqlPool=this.driverAdapter.pool??null,this.ownsPool=!0,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.driverAdapter=await Dn(e.sqlType,e.inputDetails),e.sqlPool=e.driverAdapter.pool??null,e.ownsPool=!0;}));}catch(e){this.sqlPool=null,this.ownsPool=false;for(let r of this.slaves)r.ownsPool&&(r.sqlPool=null,r.ownsPool=false);throw e}}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new S("SqlDataSource::ensureConnected","CONNECTION_NOT_ESTABLISHED");this.connecting||(this.connecting=this.connect().finally(()=>{this.connecting=null;})),await this.connecting;}}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){let e=this;return new Proxy(this._models,{get(r,n){if(typeof n=="string"&&n in r)return e.from(r[n])}})}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}getTransactionBoundSqlDataSource(){if(this.globalTransaction?.isActive)return this.globalTransaction.sql;if(this.clsEnabled){let e=He.getTransaction();if(e?.isActive&&e.sql.logicalSourceId===this.logicalSourceId)return e.sql}return null}async useCache(e,r,...n){if(!this.cacheAdapter)throw new S("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new S("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=o.length,a=typeof r=="number"&&s===n.length,l,u=[];a?(l=r,u=n):(l=void 0,u=r!==void 0?[r,...n]:n);let d=Hn(JSON.stringify(u)),c=d?`${e}:${d}`:e,m=await this.cacheAdapter.get(c);if(m!==void 0)return m;let p=await o(...u);return await this.cacheAdapter.set(c,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new S("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(n.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Hn(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.id=this.id,r.logicalSourceId=this.logicalSourceId,r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.driverAdapter=await Dn(r.sqlType,this.inputDetails),r.sqlPool=r.driverAdapter.pool,r.ownsPool=true):(r.driverAdapter=this.driverAdapter,r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let n=this.getTransactionBoundSqlDataSource()??this;if(typeof e=="string"){let o=new B(zl(e,r),n);return r?.alias&&o.table(e,r.alias),o}return new ot(e,n)}fromRaw(e,r=[],n){let o=this.getTransactionBoundSqlDataSource()??this;return new B(zl("",n),o).fromRaw(e,r)}schema(){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Wt(this,this.getDbType())}async startGlobalTransaction(e){for(;this.globalTransactionLock;)await this.globalTransactionLock;if(this.globalTransaction?.isActive)throw new S("SqlDataSource::startGlobalTransaction","GLOBAL_TRANSACTION_ALREADY_STARTED");let r=()=>{};this.globalTransactionLock=new Promise(n=>{r=n;});try{let n=await this.clone();return n.sqlConnection=await n.getConnection(),this.globalTransaction=new tr(n,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}finally{r(),this.globalTransactionLock=null;}}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new S("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");try{await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}try{await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async transaction(e,r){let n=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let o=this.clsEnabled?He.getTransaction():void 0;if(o?.isActive&&o.sql.logicalSourceId===this.logicalSourceId)return typeof e=="function"?o.nestedTransaction(e):o.nestedTransaction();let s=await this.clone();s.sqlConnection=await s.getConnection();let a=new tr(s,n?.isolationLevel);if(await a.transaction(),typeof e=="function")try{let l=this.clsEnabled?await He.run(a,()=>e(a)):await e(a);return await a.commit({throwErrorOnInactiveTransaction:!1}),l}catch(l){throw await a.rollback({throwErrorOnInactiveTransaction:false}),l}return a}getModelManager(e){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");let r=this.getTransactionBoundSqlDataSource()??this;return new st(e,r)}getPool(){if(!this.sqlPool)throw this.lazyLoad?new S("SqlDataSource::getPool - call ensureConnected() or connect() first when using lazyLoad","CONNECTION_NOT_ESTABLISHED"):new S("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;await this.ensureConnected();let e=this.driverAdapter;if(!e)throw new S("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");return e.reserveConnection()}async disconnect(){if(!this.isConnected){g.warn("Connection already closed or not established");return}if(!this.ownsPool){if(this.sqlConnection)try{this.driverAdapter?.releaseConnection(this.sqlConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing borrowed connection failed: ${e?.message??e}`);}this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}if(this.lockConnection){try{this.driverAdapter?.releaseConnection(this.lockConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing lock connection failed: ${e?.message??e}`);}this.lockConnection=null,this.lockKeyToId.clear();}await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),g.warn("Closing connection"),await this.driverAdapter?.closePool(),this.sqlPool=null,this.driverAdapter=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions,jsEnvironment:this.inputDetails.jsEnvironment,driver:this.inputDetails.driver}}async introspectSchema(){let e=this.getDbType(),r;e==="postgres"||e==="cockroachdb"?r=`
|
|
259
|
+
`)}async execute(){if(this.state!=="executed"){if(this.state==="failed")throw this.executionError;return this.then()}}isExecuted(){return this.state==="executed"}isPending(){return this.state==="pending"}hasFailed(){return this.state==="failed"}async hasTable(t){return this.dataSource.hasTable(t)}async hasColumn(t,e){return this.dataSource.hasColumn(t,e)}async hasColumns(t,...e){return this.dataSource.hasColumns(t,...e)}async hasIndex(t,e){return this.dataSource.hasIndex(t,e)}async hasPrimaryKey(t){return this.dataSource.hasPrimaryKey(t)}async hasUnique(t,e){return this.dataSource.hasUnique(t,e)}async hasForeignKey(t,e){return this.dataSource.hasForeignKey(t,e)}async hasCheckConstraint(t,e){return this.dataSource.hasCheckConstraint(t,e)}async getTables(){return this.dataSource.getTables()}async getColumnListing(t){return this.dataSource.getColumnListing(t)}dropTableIfExists(t){return this.schema.dropTable(t,true),this}async dropIndexIfExists(t,e){if(await this.dataSource.hasIndex(e,t)){let n=new ce(this.dataSource.getDbType());n.dropIndex(t,e);let o=n.queryStatements[0];o&&await this.dataSource.rawQuery(o);}}renameColumn(t,e,r){return this.schema.alterTable(t,n=>{n.renameColumn(e,r);}),this}};Hr=new WeakSet,If=async function(){try{this.state="pending";let t=this.schema.queryStatements;if(!t.length){this.state="executed";return}for(let e of t)await this.dataSource.rawQuery(e);this.state="executed";}catch(t){throw this.state="failed",this.executionError=t,t}};var Oe=class{constructor(t,e){this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var zr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}buildDropDependencies(t){let e=new Map,r=new Map,n=new Map;for(let o of t.relationsToDrop||[]){let s=`${o.table}.${o.relation.name}`,a=[];if(o.relation.referencedTable&&a.push(`table.${o.relation.referencedTable}`),o.relation.referencedColumns)for(let l of o.relation.referencedColumns)a.push(`column.${o.relation.referencedTable}.${l}`);e.set(s,a);}for(let o of t.tablesToDrop||[]){let s=`table.${o.table}`,a=[];for(let l of this.models){let u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===o.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let o of t.columnsToDrop||[]){let s=`column.${o.table}.${o.column}`,a=[],l=this.models.find(u=>u.table===o.table);if(l){let u=l.getColumns().find(d=>d.databaseName===o.column);if(u){u.isPrimary&&a.push(`pk.${o.table}`);let d=l.getRelations();for(let c of d)c.columnName===u.columnName&&a.push(`fk.${o.table}.${c.constraintName}`);}}n.set(s,a);}return {foreignKeys:e,tables:r,constraints:n}}topologicalSortReverse(t,e){let r=new Set,n=new Set,o=[],s=a=>{if(n.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;n.add(a);let l=e(a);for(let u of l)s(u);n.delete(a),r.add(a),o.push(a);};for(let a of t.keys())r.has(a)||s(a);return o}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],n=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of n){let[a,l]=s.split("."),u=t.relationsToDrop?.find(d=>d.table===a&&d.relation.name===l);u&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:u,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(u)});}let o=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let u of l)u.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):u.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of o){let a=s.replace("table.",""),l=t.tablesToDrop?.find(u=>u.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let n=[],o=this.models.find(s=>s.table===r.table);if(o){let s=o.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&n.push(`PRIMARY KEY on ${r.table}`);let a=o.getRelations();for(let l of a)l.columnName===s.columnName&&n.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,n);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let n=this.models.find(o=>o.table===r.table);n&&n.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,n=>{n.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Fl=i=>String(i??"").replace(/::[a-z_ ]+$/i,"").replace(/[()\s]/g,"").toLowerCase(),Rh=/^(current[ _]?timestamp\d*|now\d*|getdate\d*|localtimestamp\d*|localtime\d*)$/,_h={postgres:i=>i.includes("nextval"),cockroachdb:i=>i.includes("unique_rowid")},Mh={postgres:["gen_random_uuid"],cockroachdb:["gen_random_uuid"],mysql:["uuid"],mariadb:["uuid"],mssql:["newid"],sqlite:["lower(hex(randomblob(16)))"]},Ef=(i,t)=>(Mh[i]??[]).includes(Fl(t)),Rt=(i,t)=>!!i.autoCreate&&Rh.test(Fl(t)),_t=(i,t,e)=>{if(t.type!=="increment"&&t.type!=="bigIncrement")return false;let r=_h[i];return r?r(Fl(e)):false};var Gr=class Gr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new zr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,n=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),o=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...n].filter(l=>o.has(l)));return e.filter(l=>{let u=r(l);return u?!(s.has(u)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let n=this.sql.schema().createTable(r.table,o=>{for(let s of r.columns){if(Array.isArray(s.type)){o.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,o,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[n]});}for(let r of t.columnsToAdd){let n=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:n});}return e}generateConstraintCreationOperations(t){let e=[];for(let n of t.uniquesToDrop||[]){let o=this.sql.schema().alterTable(n.table,s=>{s.dropConstraint(n.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:o});}let r=new Set((t.uniquesToDrop||[]).map(n=>n.name));for(let n of t.indexesToDrop){if(r.has(n.index))continue;let o=new ce(this.sql.getDbType());o.dropIndex(n.index,n.table);let s=o.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[s]});}for(let n of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===n.table)?.getColumns().find(u=>u.columnName===n.columns[0])?.primaryKeyConstraintName||qe(n.table,n.columns[0]),l=this.sql.schema().alterTable(n.table,u=>{let d=a||qe(n.table,n.columns[0]);u.addConstraint("primary_key",{columns:[n.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:a,data:n,dependencies:[`table.${n.table}`],sqlStatements:l});}for(let n of t.relationsToAdd){if(n.relation.type==="manyToMany")continue;let o=this.generateAddRelationViaAlter(n),s=this.computeFkConstraintName(n);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:n.table,constraint:s,data:n,dependencies:this.getForeignKeyDependencies(n),sqlStatements:o});}for(let n of t.uniquesToAdd||[]){let o=this.models.find(l=>l.table===n.table),s=(n.columns||[]).map(l=>o?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(n.table,l=>{l.addConstraint("unique",{columns:s,constraintName:n.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name||"mandatory",data:n,dependencies:[`table.${n.table}`],sqlStatements:a});}for(let n of t.indexesToAdd){let o=this.generateCreateIndexSql(n);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:n.table,index:n.index,data:n,dependencies:[`table.${n.table}`],sqlStatements:[o]});}for(let n of t.checksToDrop||[]){let o=new ce(this.sql.getDbType());o.dropCheck(n.table,n.name);let s=o.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}for(let n of t.checksToAdd||[]){let o=new ce(this.sql.getDbType());o.addCheck(n.table,n.expression,{constraintName:n.name});let s=o.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:n.table,constraint:n.name,data:n,dependencies:[`table.${n.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=C(t.relation.constraintName);if(e)return e;let r=t.table;t.relation.type==="belongsTo"?r=t.relation.model().table:t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(r=C(t.relation.manyToManyOptions.throughModel));let o=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=o.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=o.find(l=>l.columnName===s)?.databaseName||s,Z(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let n=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:n});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let n=t.relation.model();e.push(`table.${n.table}`);let o=n.primaryKey||"id",s=n.getColumns().find(a=>a.columnName===o);s&&e.push(`column.${n.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let n=C(t.relation.manyToManyOptions.throughModel);e.push(`table.${n}`);}e.push(`table.${t.table}`);let r=this.models.find(n=>n.table===t.table);if(r){let n=r.getColumns().find(o=>o.columnName===t.relation.columnName||o.databaseName===t.relation.columnName);n&&e.push(`column.${t.table}.${n.databaseName}`);}return e}applyNullableConstraint(t,e){return e===false?t.notNullable():e===true||this.sql.getDbType()==="mariadb"?t.nullable():t}executeBuilderMethod(t,e,r,n,o=true){let s;if(Array.isArray(r.type))s=e.enum(n[0],r.type);else if(typeof r.type=="string"&&Gr.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...n);else if(typeof r.type=="string")s=e.custom(n[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return o&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||qe(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),this.applyNullableConstraint(s,r.constraints?.nullable)),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(n=>{let o=this.executeBuilderMethod(t.table,n,t.column,e,false);return t.column.constraints?.default!==void 0&&o.default(t.column.constraints.default),this.applyNullableConstraint(o,t.column.constraints?.nullable),o});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,n=>{n.alterColumn(o=>{let s=this.executeBuilderMethod(t.table,o,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&!Rt(t.modelColumn,t.dbColumns.defaultValue)&&!_t(this.sql.getDbType(),t.modelColumn,t.dbColumns.defaultValue)&&s.default(null),this.applyNullableConstraint(s,t.modelColumn.constraints?.nullable),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),n=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),o=new ce(this.sql.getDbType());return o.createIndex(t.table,n,{constraintName:t.index}),o.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=C(t.relation.manyToManyOptions.throughModel),r=C(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let n=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,o=C(r);if(t.relation.type==="belongsTo"){let m=t.relation.model(),p=m.primaryKey,f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=H(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.model();if(typeof o=="string"&&o){let p=m.getColumns(),h=p.find(f=>f.columnName===o);if(h)o=h.databaseName;else {let f=m.primaryKey||"id",T=p.find(w=>w.columnName===f);if(T)o=T.databaseName;else {let w=m?.databaseCaseConvention||"preserve";o=H(o||f,w);}}}else {let p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p);if(f)o=f.databaseName;else {let T=m?.databaseCaseConvention||"preserve";o=H(p,T);}}}let s=this.models.find(m=>m.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(m=>m.columnName===l);if(u)l=u.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=H(l,m);}if(t.relation.type==="belongsTo"){let m=a.find(p=>p.columnName===t.relation.foreignKey);if(m)l=m.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=H(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.manyToManyOptions.leftForeignKey,p=C(m),h=a.find(f=>f.columnName===p);if(h)l=h.databaseName;else {let f=s?.databaseCaseConvention||"preserve";l=H(p,f);}}let d=t.relation.onDelete?.toLowerCase(),c=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,m=>{let p=n||Z(t.table,l,e);m.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[o]},constraintName:p,onDelete:d,onUpdate:c});}).toQueries()}formatSqlStatements(t){return t.map(e=>({...e,sqlStatements:e.sqlStatements.map(r=>format(r,{...this.sql.inputDetails.queryFormatOptions}).replace(/\n/g," ").replace(/\s+/g," "))}))}};Gr.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var jt=Gr;var Zr=class Zr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],n=null,o={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==n&&(n=s.phase,e.length>0&&e.push(""),e.push(`// ${o[n]}`));let{up:a,down:l}=this.generateOperationCode(s);a&&e.push(...a),l&&r.push(...l);}return {up:e,down:r}}generateOperationCode(t){switch(t.type){case "CREATE_TABLE":return this.generateCreateTableCode(t);case "ADD_COLUMN":return this.generateAddColumnCode(t);case "MODIFY_COLUMN":return this.generateModifyColumnCode(t);case "DROP_COLUMN":return this.generateDropColumnCode(t);case "CREATE_INDEX":return this.generateCreateIndexCode(t);case "DROP_INDEX":return this.generateDropIndexCode(t);case "ADD_FOREIGN_KEY":return this.generateAddForeignKeyCode(t);case "DROP_FOREIGN_KEY":return this.generateDropForeignKeyCode(t);case "ADD_UNIQUE_CONSTRAINT":return this.generateAddUniqueCode(t);case "DROP_CONSTRAINT":return this.generateDropConstraintCode(t);case "ADD_CHECK_CONSTRAINT":return this.generateAddCheckCode(t);case "ADD_PRIMARY_KEY":return this.generateAddPrimaryKeyCode(t);case "DROP_TABLE":return this.generateDropTableCode(t);case "MODIFY_PRIMARY_KEY":return this.generateModifyPrimaryKeyCode(t);default:return {up:null,down:null}}}generateCreateTableCode(t){let e=t.data,r=[];r.push(`this.schema.createTable(${this.quote(e.table)}, (table) => {`);for(let o of e.columns){let s=this.generateColumnCode(e.table,o,true);r.push(` ${s}`);}r.push("});");let n=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:n}}generateAddColumnCode(t){let{table:e,column:r}=t.data,n=this.generateColumnCode(e,r,false),o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:o,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:n}=t.data,o=this.generateColumnCodeForModify(e,r,n),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(n.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],o=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:n,down:o}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u),s=o.length===1?this.quote(o[0]):`[${o.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.createIndex(${this.quote(e.table)}, ${s}, { constraintName: ${this.quote(e.index)} });`],l=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`];return {up:a,down:l}}generateDropIndexCode(t){let e=t.data,r=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`],n=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:n}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:n,referencedColumn:o,constraintName:s}=this.resolveRelationDetails(e),a=e.relation.onDelete?.toLowerCase(),l=e.relation.onUpdate?.toLowerCase(),u=[];s&&u.push(`constraintName: ${this.quote(s)}`),a&&u.push(`onDelete: ${this.quote(a)}`),l&&u.push(`onUpdate: ${this.quote(l)}`);let d=u.length>0?`, { ${u.join(", ")} }`:"",c=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(n)}, ${this.quote(o)}${d});`,"});"],m=s||Z(e.table,r,n),p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(m)});`,"});"];return {up:c,down:p}}generateDropForeignKeyCode(t){let e=t.constraint||t.data?.relation?.name;if(!e)return {up:null,down:null};let r=t.table||t.data?.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],o=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:n,down:o}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),o=`[${(e.columns||[]).map(u=>r?.getColumns().find(c=>c.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${o}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,n=t.constraint||e.name;if(!n||!r)return {up:null,down:null};if(e.type==="primary_key"){let a=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});"],l=[`// TODO: reverse primary key drop on ${this.quote(r)}`];return {up:a,down:l}}if(e.type==="unique"){let a=e.column,l=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(n)});`,"});"],u=[`// TODO: reverse unique constraint drop for ${this.quote(a)} on ${this.quote(r)}`];return {up:l,down:u}}if(e.expression!==void 0){let a=[`this.schema.dropCheck(${this.quote(r)}, ${this.quote(n)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:a,down:l}}let o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(n)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(n)} on ${this.quote(r)}`];return {up:o,down:s}}generateAddCheckCode(t){let e=t.data,r=[`this.schema.addCheck(${this.quote(e.table)}, ${this.quote(e.expression)}, { constraintName: ${this.quote(e.name)} });`],n=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:n}}generateAddPrimaryKeyCode(t){let e=t.data,o=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||qe(e.table,e.columns[0]),s=`[${e.columns.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.addConstraint("primary_key", { columns: ${s}, constraintName: ${this.quote(o)} });`,"});"],l=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`," table.dropPrimaryKey();","});"];return {up:a,down:l}}generateDropTableCode(t){let e=t.table||t.data?.table,r=[`this.schema.dropTable(${this.quote(e)});`],n=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:n}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],o=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:n,down:o}}generateColumnCode(t,e,r){let n=this.generateColumnTypeCode(e);if(!r)return n;if(e.isPrimary){let o=e.primaryKeyConstraintName||qe(t,e.columnName);n+=`.primaryKey({ constraintName: ${this.quote(o)} })`;}return e.unsigned&&(n+=".unsigned()"),e.zerofill&&(n+=".zerofill()"),e.constraints?.default!==void 0&&(n+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n+";"}generateColumnCodeForModify(t,e,r){let n=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?n+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&!Rt(e,r.defaultValue)&&!_t(this.sql.getDbType(),e,r.defaultValue)&&(n+=".default(null)"),e.constraints?.nullable===false?n+=".notNullable()":e.constraints?.nullable===true&&(n+=".nullable()"),n}generateColumnTypeCode(t){let e=t.databaseName;if(Array.isArray(t.type)){let s=t.type.map(a=>this.quote(a)).join(", ");return `table.enum(${this.quote(e)}, [${s}])`}let r=t.type;if(new Set(["uuid","ulid","boolean","year","json","jsonb","binary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]).has(r))return `table.${r}(${this.quote(e)})`;if(r==="timestamp"||r==="datetime"){let s=[];return t.withTimezone&&s.push("withTimezone: true"),t.precision!=null&&s.push(`precision: ${t.precision}`),s.length>0?`table.${r}(${this.quote(e)}, { ${s.join(", ")} })`:`table.${r}(${this.quote(e)})`}return r==="date"||r==="time"?t.precision!=null?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="increment"||r==="bigIncrement"?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:r==="decimal"||r==="numeric"?t.precision!=null?t.scale!=null?`table.${r}(${this.quote(e)}, ${t.precision}, ${t.scale})`:`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="float"||r==="double"||r==="real"?t.precision!=null&&t.precision!==10?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="longtext"||r==="mediumtext"||r==="tinytext"?`table.${r}(${this.quote(e)})`:new Set(["varchar","char","string","integer","tinyint","smallint","mediumint","bigint","biginteger","varbinary"]).has(r)?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:Zr.BUILTIN_COLUMN_TYPES.has(r)?`table.${r}(${this.quote(e)})`:t.length!=null?`table.custom(${this.quote(e)}, ${this.quote(r)}, ${t.length})`:`table.custom(${this.quote(e)}, ${this.quote(r)})`}resolveRelationDetails(t){let e=t.table,r="id";if(t.relation.type==="belongsTo"){let l=t.relation.model();e=l.table;let u=l.primaryKey||"id";r=l.getColumns().find(m=>m.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=C(t.relation.manyToManyOptions.throughModel);let l=C(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let o=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=o.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=C(t.relation.manyToManyOptions.leftForeignKey);s=o.find(d=>d.columnName===l)?.databaseName||l;}else s=o.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName:C(t.relation.constraintName)||void 0;return {sourceColumn:s,referencedTable:e,referencedColumn:r,constraintName:a}}quote(t){return `"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}formatDefaultValue(t){return t==null?"null":t==="NULL"?'"NULL"':typeof t=="boolean"||typeof t=="number"?t.toString():t==="TRUE"||t==="true"?"true":t==="FALSE"||t==="false"?"false":this.quote(String(t))}};Zr.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var Yr=Zr;function Oh(i){return i.replace(/\s+/g," ").trim()}function Dh(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ah(i){let t=i.split(/\s+/).filter(n=>n.length>0),e=[],r=[];for(let n of t)n==="unsigned"||n==="zerofill"?e.push(n):r.push(n);return {bareBase:r.join(" "),modifiers:e}}function $h(i,t){return t.length===0?i:`${i} ${t.join(" ")}`}function Ue(i,t){let e=Oh(t.toLowerCase()),r=Dh(e);switch(i){case "sqlite":{let n=[{test:o=>o==="increment",normalized:"integer"},{test:o=>o==="bigincrement",normalized:"integer"},{test:o=>o.includes("int"),normalized:"integer"},{test:o=>o==="string",normalized:"varchar"},{test:o=>o.includes("char"),normalized:"varchar"},{test:o=>o.includes("text"),normalized:"text"},{test:o=>o.includes("clob"),normalized:"text"},{test:o=>o.includes("date"),normalized:"text"},{test:o=>o.includes("time"),normalized:"text"},{test:o=>o.includes("timestamp"),normalized:"text"},{test:o=>o.includes("datetime"),normalized:"text"},{test:o=>o.includes("blob"),normalized:"blob"},{test:o=>o.includes("real")||o.includes("floa")||o.includes("doub"),normalized:"real"},{test:o=>o.includes("numeric"),normalized:"numeric"},{test:o=>o.includes("bool"),normalized:"integer"},{test:o=>o.includes("uuid"),normalized:"varchar"},{test:o=>o.includes("ulid"),normalized:"varchar"},{test:o=>o.includes("jsonb"),normalized:"text"},{test:o=>o.includes("json"),normalized:"text"}];for(let o of n)if(o.test(r))return o.normalized;return r}case "mysql":case "mariadb":{let{bareBase:n,modifiers:o}=Ah(r),a=new Set(["int","integer","increment","tinyint","smallint","mediumint","bigint","bigincrement","float","double","double precision","real","decimal","numeric","year","bool","boolean"]).has(n);if(n.endsWith("text")||n==="text")return "text";let l;switch(n){case "int":case "integer":case "increment":l="integer";break;case "tinyint":l="boolean";break;case "smallint":l="smallint";break;case "mediumint":l="mediumint";break;case "bigint":case "bigincrement":l="bigint";break;case "float":l="float";break;case "double":case "double precision":l="double";break;case "real":l="double";break;case "decimal":case "numeric":l="numeric";break;case "string":case "varchar":case "character varying":l="varchar";break;case "char":case "character":l="char";break;case "uuid":l="varchar";break;case "ulid":l="varchar";break;case "date":l="date";break;case "datetime":l="datetime";break;case "timestamp":l="timestamp";break;case "time":l="time";break;case "year":l="year";break;case "jsonb":case "json":l=i==="mariadb"?"text":"json";break;case "enum":l="enum";break;case "binary":l="binary";break;case "varbinary":l="varbinary";break;case "tinyblob":l="tinyblob";break;case "mediumblob":l="mediumblob";break;case "longblob":l="longblob";break;case "blob":l="blob";break;case "boolean":case "bool":l="boolean";break;default:l=n;break}return a&&o.length>0?$h(l,o):l}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}default:return r}}var rt=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql._models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let n=await e.sql.getTableSchema(r.table),o={columns:r.getColumns().filter(f=>f?.type!==void 0&&f?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!n.columns.length){e.data.tablesToAdd.push({table:r.table,columns:o.columns});for(let w of o.indexes)n.indexes.map(q=>q.name).includes(w.name)||e.data.indexesToAdd.push({table:r.table,index:w.name});let f=r.getUniques?.()||[];for(let w of f)e.data.uniquesToAdd.push({table:r.table,name:w.name||"mandatory",columns:w.columns});let T=r.getChecks?.()||[];for(let w of T)e.data.checksToAdd.push({table:r.table,name:w.name,expression:w.expression});for(let w of o.relations){if(w.type!=="belongsTo")continue;let q=C(w.constraintName);n.foreignKeys.find(R=>R.name===q)||e.data.relationsToAdd.push({table:r.table,relation:w,onDelete:w.onDelete,onUpdate:w.onUpdate});}return}for(let f of o.columns)n.columns.some(w=>w.name===f.databaseName||w.name===f.columnName)||e.data.columnsToAdd.push({table:r.table,column:f});let s=r.getColumns();for(let f of n.columns)s.some(w=>w.databaseName===f.name||w.columnName===f.name)||e.data.columnsToDrop.push({table:r.table,column:f.name});for(let f of o.indexes)n.indexes.map(T=>T.name).includes(f.name)||e.data.indexesToAdd.push({table:r.table,index:f.name});let a=r.getUniques?.()||[];for(let f of a)n.indexes.some(w=>w.name===f.name&&w.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:f.name||"mandatory",columns:f.columns});let l=n.foreignKeys.map(f=>f.name);for(let f of n.indexes)f.isUnique||l.includes(f.name)||o.indexes.map(w=>w.name).includes(f.name)||e.data.indexesToDrop.push({table:r.table,index:f.name});for(let f of n.indexes){if(!f.isUnique||f.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(w=>w.name).includes(f.name)||e.data.uniquesToDrop.push({table:r.table,name:f.name});}let u=r.getChecks?.()||[];for(let f of u)n.checkConstraints.some(w=>w.name===f.name)||e.data.checksToAdd.push({table:r.table,name:f.name,expression:f.expression});let d=new Set(u.map(f=>f.name)),c=o.columns.filter(f=>Array.isArray(f.type)),m=new Set(c.map(f=>f.databaseName||f.columnName));for(let f of n.checkConstraints)if(!d.has(f.name)){let T=[...m].find(w=>{let q=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),D=new RegExp(`[\\["\\[]?${q}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i"),R=new RegExp(`[\\("\\[]?${q}[\\)"\\]]?(?:::text)?\\s*=\\s*ANY\\s*\\(`,"i");return D.test(f.expression)||R.test(f.expression)});if(T){let w=c.find(D=>(D.databaseName||D.columnName)===T),q=n.columns.find(D=>D.name===T);if(w&&q?.enumValues&&Array.isArray(w.type)){let D=[...w.type].sort(),R=[...q.enumValues].sort();if(!(D.length===R.length&&D.every((A,O)=>A===R[O]))){e.data.checksToDrop.push({table:r.table,name:f.name});let A=e.sql.getDbType(),O=A==="mssql"?"[":'"',K=A==="mssql"?"]":'"',le=w.type.map(v=>`'${v.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:f.name,expression:`${O}${T}${K} IN (${le})`});}}}else e.data.checksToDrop.push({table:r.table,name:f.name});}for(let f of o.columns){let T=n.columns.find(D=>D.name===f.databaseName||D.name===f.columnName);if(!T)continue;let w=!e.areColumnsEqual(T,f,n.indexes),q=e.getDefaultChange({table:r.table,dbColumns:T,modelColumn:f});(w||q)&&e.data.columnsToModify.push({table:r.table,dbColumns:T,modelColumn:f});}for(let f of o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;if(f.type==="manyToMany"&&f.manyToManyOptions){let q=C(f.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:q,relation:{type:"belongsTo",model:()=>r,columnName:C(f.manyToManyOptions.leftForeignKey),foreignKey:f.manyToManyOptions.leftForeignKey,constraintName:f.constraintName?C(f.constraintName):Z(q,C(f.manyToManyOptions.leftForeignKey||Ll(r.table)),r.table),onDelete:f.onDelete,onUpdate:f.onUpdate},onDelete:f.onDelete,onUpdate:f.onUpdate});continue}let T=C(f.constraintName);if(T&&n.foreignKeys.some(q=>q.name===T))continue;n.foreignKeys.find(q=>e.relationMatchesDbRelation(r,f,q))||e.data.relationsToAdd.push({table:r.table,relation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let p=new Set(o.relations.filter(f=>f.type==="belongsTo").map(f=>{let T=C(f.foreignKey)||f.columnName,q=r.getColumns().find(D=>D.columnName===T)?.databaseName||T;return C(f.constraintName)||Z(r.table,q,f.model().table)}));for(let f of n.foreignKeys){if(f.name&&p.has(f.name))continue;o.relations.find(w=>w.type!=="belongsTo"&&w.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,w,f))||e.data.relationsToDrop.push({table:r.table,relation:f});}for(let f of o.relations){if(f.type!=="belongsTo"&&f.type!=="manyToMany")continue;let T=n.foreignKeys.find(w=>e.relationMatchesDbRelation(r,f,w));T&&!e.areRelationsEqual(T,f)&&e.data.relationsToModify.push({table:r.table,dbRelation:T,modelRelation:f,onDelete:f.onDelete,onUpdate:f.onUpdate});}let h=r.primaryKey;if(h&&!n.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[h]}),n.primaryKey&&!h&&e.data.primaryKeysToDrop.push({table:r.table,columns:n.primaryKey.columns,name:n.primaryKey.name}),h&&n.primaryKey){let f=r.getColumns().find(T=>T.columnName===h);f&&!e.arePrimaryKeysEqual(n.primaryKey,f)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:n.primaryKey,modelPrimaryKey:h});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let n=r.trim();return n?!this.emptyStatements.some(o=>o.test(n)):false})}getCodeStatements(){let e=new jt(this.sql).generateOperations(this.data);return new Yr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new jt(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),n={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let o of r)n[o.phase].push(...o.sqlStatements);return n}areColumnsEqual(t,e,r=[]){let n=t.name===e.databaseName,o=this.sql.getDbType(),s=Ue(o,t.dataType),a=typeof e.type=="string"?Ue(o,e.type):void 0,l=s.split(" ").filter(d=>d!=="unsigned"&&d!=="zerofill").join(" ");if(a&&n&&(n=l===a),Array.isArray(e.type)&&(o==="mysql"||o==="mariadb")){let d=[...e.type].sort(),c=t.enumValues?[...t.enumValues].sort():null;c&&n&&(n=d.length===c.length&&d.every((m,p)=>m===c[p]));}e.length!=null&&t.length!=null&&n&&(n=t.length===e.length);let u=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((o==="postgres"||o==="cockroachdb")&&u||n&&(n=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(o==="postgres"||o==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&n&&(n=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,c=t.isNullable;n=n&&d===c;}if(o==="mysql"||o==="mariadb"){if(e.unsigned!==void 0){let d=e.unsigned??false,c=t.unsigned??false;n&&(n=d===c);}if(e.zerofill!==void 0){let d=e.zerofill??false,c=t.zerofill??false;n&&(n=d===c);}}if(e.stringMode!==void 0){let d=e.stringMode??false,c=t.stringMode??false;n&&(n=d===c);}return n}areRelationsEqual(t,e){let r=C(e.constraintName),n=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",c=u.getColumns().find(h=>h.columnName===d),m=u.table,p=c?.databaseName||d;n=n&&t.referencedTable===m&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=C(e.manyToManyOptions.throughModel);n=n&&t.referencedTable===u;}let o=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&n&&(n=o===a),l&&n&&(n=s===l),n}relationMatchesDbRelation(t,e,r){let n,o=e;if(o&&o.model){if(typeof o.model=="function"&&o.model.table)n=o.model;else if(typeof o.model=="function")try{let f=o.model();f&&f.table&&(n=f);}catch{}}if(!n)return false;let s=e.type==="belongsTo"?n.table:e.type==="manyToMany"&&e.manyToManyOptions?C(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=C(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),d=(o.type||"belongsTo")==="belongsTo"?C(o.foreignKey):o.columnName,c=l.find(f=>f.columnName===d);c&&(d=c.databaseName);let m=n.primaryKey||"id",h=n.getColumns().find(f=>f.columnName===m)?.databaseName||m;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let n=t.columns[0]===e.databaseName,o=this.sql.getDbType();if(["mysql","mariadb"].includes(o))return n;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return n&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Ue(e,t.dbColumns.dataType),n=typeof t.modelColumn.type=="string"?Ue(e,t.modelColumn.type):void 0;if(n&&r!==n||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(n==="timestamp"||n==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0;if(s&&!a)return "set";if(!s&&a){let l=t.dbColumns.defaultValue;return _t(e,t.modelColumn,l)||Rt(t.modelColumn,l)||t.modelColumn.type==="uuid"&&Ef(e,l)?false:"drop"}if(s&&a){let l=String(t.dbColumns.defaultValue),u=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,l),c=this.normalizeDefaultValue(e,n||r,u);return d!==c?"set":false}return false}normalizeDefaultValue(t,e,r){let n=String(r).trim();if(!n)return n;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=n.match(/^'(.*)'$/s);if(s&&(n=s[1]),n==="{}"||n==="")return "{}";let a=JSON.parse(n);return JSON.stringify(a)}catch{}n=n.replace(/^\((.*)\)$/s,"$1"),n=n.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),/^true$/i.test(n)?"true":/^false$/i.test(n)?"false":/^null$/i.test(n)?"null":(n)}if(t==="mysql"||t==="mariadb"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);if(o&&(n=o[1]),/^current_timestamp(?:\(\d+\))?$/i.test(n))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(n))return "true";if(/^0$/.test(n))return "false"}return n}if(t==="sqlite"){n=n.replace(/^\((.*)\)$/s,"$1");let o=n.match(/^'(.*)'$/s);return o&&(n=o[1]),n.toLowerCase()}return n}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let n of r){if(n.type!=="manyToMany"||!n.manyToManyOptions||n.manyToManyOptions.wasModelProvided)continue;let o=C(n.manyToManyOptions.throughModel);if(t.has(o))continue;t.add(o);let s=this.models.find(v=>v.table===n?.manyToManyOptions?.primaryModel),a=n.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find(v=>v.columnName===l),c=a.getColumns().find(v=>v.columnName===u);if(!d||!c)continue;let m=C(n.manyToManyOptions.leftForeignKey)||l,p=C(n.manyToManyOptions.rightForeignKey)||u,h=await this.sql.getTableSchema(o);if(!h.columns.length){this.data.tablesToAdd.push({table:o,columns:[this.clonePkAsColumn(d,m),this.clonePkAsColumn(c,p)]}),this.pushM2mFkRelations({throughTable:o,leftModel:s,rightModel:a,leftFkName:m,rightFkName:p,onDelete:n.onDelete,onUpdate:n.onUpdate,constraintName:void 0});continue}let f=this.clonePkAsColumn(d,m),T=this.clonePkAsColumn(c,p),w=h.columns.find(v=>v.name===m),q=h.columns.find(v=>v.name===p),D=w?this.areColumnsEqual(w,f,h.indexes):false,R=q?this.areColumnsEqual(q,T,h.indexes):false;for(let v of h.foreignKeys){let ne=v.referencedTable===s.table,Ye=v.referencedTable===a.table;if(!ne&&!Ye)continue;let _e=ne?m:p,Me=v.columns[0];Me&&Me!==_e&&(this.data.relationsToDrop.push({table:o,relation:v}),Me!==m&&Me!==p&&this.data.columnsToDrop.push({table:o,column:Me}));}let $={};D||($[f.databaseName]=f),R||($[T.databaseName]=$[T.databaseName]||T);for(let v of Object.keys($))this.data.columnsToAdd.push({table:o,column:$[v]});let A=this.buildBelongsToRelation(o,()=>s,m,l,void 0,n.onDelete,n.onUpdate),O=this.buildBelongsToRelation(o,n.model,p,u,void 0,n.onDelete,n.onUpdate),K=h.foreignKeys.find(v=>v.referencedTable===s.table&&v.columns.length===1&&v.columns[0]===m),le=h.foreignKeys.find(v=>v.referencedTable===a.table&&v.columns.length===1&&v.columns[0]===p);if(!K){let v=h.foreignKeys.find(ne=>ne.referencedTable===s.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(A);}if(!le){let v=h.foreignKeys.find(ne=>ne.referencedTable===a.table);v&&this.data.relationsToDrop.push({table:o,relation:v}),this.data.relationsToAdd.push(O);}}}}async removeFkChurnByName(){let t=new Set;for(let n of this.data.relationsToAdd)t.add(n.table);for(let n of this.data.relationsToDrop)t.add(n.table);let e=new Map;for(let n of t){let o=await this.sql.getTableSchema(n),s=new Set((o.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(n,s);}let r=new Map;for(let n of this.models){let o=n.getRelations(),s=new Set;for(let a of o){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=n.getColumns().find(m=>m.columnName===l)?.databaseName||l,c=C(a.constraintName)||Z(n.table,d,a.model().table);s.add(c);}r.set(n.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async n=>{let o=await this.sql.getTableSchema(n.table),s=this.models.find(f=>f.table===n.table),a=s?.getColumns()||[],l=n.relation.columnName;n.relation.type==="belongsTo"?l=a.find(T=>T.columnName===n.relation.foreignKey)?.databaseName||n.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let u=n.table,d=n.relation.foreignKey;if(n.relation.type==="belongsTo"){let f=n.relation.model();u=f.table;let T=f.primaryKey||"id";d=f.getColumns().find(q=>q.columnName===T)?.databaseName||T;}let c=new Set([l,n.relation.columnName].filter(Boolean)),m=o.foreignKeys.some(f=>{if(f.columns.length!==1||f.referencedColumns.length!==1)return false;let T=c.has(f.columns[0]),w=f.referencedTable===u,q=f.referencedColumns[0]===d;return T&&w&&q}),p=C(n.relation.constraintName)||Z(n.table,l,u),h=e.get(n.table)||new Set;if(m||p&&h.has(p))return null;if(n.relation.type==="manyToMany"&&n.relation.manyToManyOptions){let f=C(n.relation.manyToManyOptions.throughModel),T=C(n.relation.manyToManyOptions.leftForeignKey),w=C(n.relation.manyToManyOptions.rightForeignKey),q=n.table===f&&n.relation.columnName===T&&n.relation.model().table===s?.table,D=n.table===f&&n.relation.columnName===w&&n.relation.model().table!==s?.table,R=await this.sql.getTableSchema(f),$=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===T&&O.referencedTable===(s?.table||"")),A=R.foreignKeys.some(O=>O.columns.length===1&&O.columns[0]===w&&O.referencedTable===n.relation.model().table);if(q&&$||D&&A)return null}return n})).then(n=>n.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async n=>{let o=this.models.find(u=>u.table===n.table);if(!o)return n;let s=o.getRelations(),a=o.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let c=a.find(T=>T.columnName===u.foreignKey)?.databaseName||u.foreignKey,m=u.model(),p=m.primaryKey||"id",f=m.getColumns().find(T=>T.columnName===p)?.databaseName||p;return n.relation.columns.length===1&&n.relation.columns[0]===c&&n.relation.referencedTable===m.table&&n.relation.referencedColumns.length===1&&n.relation.referencedColumns[0]===f})?null:n})).then(n=>n.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,n,o,s,a){let l=o?C(o):Z(t,r,e().table);return {table:t,relation:{type:"belongsTo",model:e,columnName:r,foreignKey:r,constraintName:l,onDelete:s,onUpdate:a},onDelete:s,onUpdate:a}}};var Ve=class{};Ve.modelCaseConvention="camel",Ve.databaseCaseConvention="snake";var Bf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");return o+=n.final("hex"),`${r.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptSymmetric","FAILED_TO_ENCRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},kf=(i,t)=>{try{let e=Pe.createHash("sha256").update(i).digest(),r=String(t).trim(),[n,o]=r.split(":");if(!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:data" but got "${r.substring(0,50)}..."`);let s=n.toLowerCase(),a=o.toLowerCase(),l=Pe.createDecipheriv("aes-256-cbc",e,Buffer.from(s,"hex")),u=l.update(a,"hex","utf8");return u+=l.final("utf8"),u}catch(e){throw new S("Encryption::decryptSymmetric","FAILED_TO_DECRYPT_SYMMETRICALLY",e instanceof Error?e:void 0)}},Kf=(i,t)=>{try{let e=Pe.randomBytes(32),r=Pe.randomBytes(16),n=Pe.createCipheriv("aes-256-cbc",e,r),o=n.update(t,"utf8","hex");o+=n.final("hex");let s=publicEncrypt(i,e);return `${r.toString("hex")}:${s.toString("hex")}:${o}`}catch(e){throw new S("Encryption::encryptAsymmetric","FAILED_TO_ENCRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}},Qf=(i,t)=>{try{let e=String(t).trim(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error(`Invalid encrypted value format: expected "iv:key:data" but got "${e.substring(0,50)}..."`);let s=privateDecrypt(i,Buffer.from(n,"hex")),a=Pe.createDecipheriv("aes-256-cbc",s,Buffer.from(r,"hex")),l=a.update(o,"hex","utf8");return l+=a.final("utf8"),l}catch(e){throw new S("Encryption::decryptAsymmetric","FAILED_TO_DECRYPT_ASYMMETRICALLY",e instanceof Error?e:void 0)}};var z=class{static defineMetadata(t,e,r,n){if((typeof r!="object"||r===null)&&typeof r!="function")throw new TypeError("target must be an object or function");let o=this.store.get(r);o||(o=new Map,this.store.set(r,o));let s=o.get(n);s||(s=new Map,o.set(n,s)),s.set(t,e);}static getMetadata(t,e,r){if((typeof e!="object"||e===null)&&typeof e!="function")throw new TypeError("target must be an object or function");let n=e;for(;n;){let o=this.store.get(n);if(o){let s=o.get(r);if(s&&s.has(t))return s.get(t)}n=Object.getPrototypeOf(n);}}};z.store=new WeakMap;var Vl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ul=Vl.length,Ph=10,Eh=16,Bh=(i,t)=>{let e="";for(let r=0;r<t;r++){let n=i%Ul;e=Vl.charAt(n)+e,i=(i-n)/Ul;}return e},kh=i=>{let t=ie().crypto.randomBytes(i),e="";for(let r=0;r<i;r++){let n=t[r];e+=Vl.charAt(n%Ul);}return e},Lf=()=>{let i=Math.floor(Date.now()/1e3),t=Bh(i,Ph),e=kh(Eh);return t+e};var Xr=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var en=class extends Oe{constructor(e,r,n){super(e,r);this.type="hasMany";this.foreignKey=n,this.type="hasMany";}};var tn=class extends Oe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var rn=class extends Oe{constructor(e,r,n){super(e,r);this.type="manyToMany";this.primaryModel=n.primaryModel,this.relatedModel=e.table,this.throughModel=n.throughModel,this.leftForeignKey=n.leftForeignKey,this.rightForeignKey=n.rightForeignKey;}};function _(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let n=e.constructor;if(t){if(z.getMetadata(Ct,e))throw new S("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");z.defineMetadata(Ct,r,e),z.defineMetadata(Ct,r,e.constructor);}let o=i.databaseName??H(r,n.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??qe(n.table,r),autoUpdate:i.autoUpdate,autoCreate:i.autoCreate,databaseName:o,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,unsigned:i.unsigned,zerofill:i.zerofill,stringMode:i.stringMode,expression:i.expression,constraints:{nullable:i.nullable,default:i.default}};s.validate=i.validate;let a=z.getMetadata(jr,e)||[];a.push(s),z.defineMetadata(jr,a,e);}}_.primary=Kh;_.date=tg;_.datetime=rg;_.timestamp=ng;_.time=og;_.boolean=eg;_.json=sg;_.uuid=Fh;_.ulid=Uh;_.integer=Lh;_.bigInteger=Hh;_.float=Qh;_.decimal=zh;_.increment=Wh;_.bigIncrement=jh;_.string=Vh;_.text=Jh;_.binary=Gh;_.enum=Yh;_.encryption={symmetric:Zh,asymmetric:Xh};_.computed=ig;function Kh(i={}){return _({...i,primaryKey:true})}function Qh(i={}){return _({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?Number.parseInt(t):Number.parseFloat(t)},openApi:{type:"number",format:"float",description:"A floating point number",...i.openApi||{}}})}function Lh(i={}){return _({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An integer number",...i.openApi||{}}})}function Wh(i={}){return _({type:"increment",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing integer number",...i.openApi||{}}})}function jh(i={}){return _({type:"bigIncrement",...i,primaryKey:true,nullable:false,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseInt(t)},openApi:{type:"integer",format:"int64",description:"An auto-incrementing bigint number",...i.openApi||{}}})}function Fh(i={}){return _({type:"uuid",...i,prepare:t=>t||ie().crypto.randomUUID(),openApi:{type:"string",format:"uuid",description:"uuid (Universally Unique Identifier)",...i.openApi||{}}})}function Uh(i={}){return _({type:"ulid",...i,prepare:t=>t||Lf(),openApi:{type:"string",format:"ulid",description:"ulid (Universally Unique Lexicographically Sortable Identifier)",...i.openApi||{}}})}function Vh(i={}){return _({type:"string",...i,openApi:{type:"string",description:"A string value",...i.openApi||{}}})}function Jh(i={}){return _({type:"longtext",...i,openApi:{type:"string",description:"A text value",...i.openApi||{}}})}function Hh(i={}){return _({type:"bigint",...i,serialize:t=>{if(t!==void 0){if(t===null)return null;if(typeof t=="number")return t;if(typeof t=="string")return Number.parseInt(t);if(typeof t=="bigint")return Number(t)}},openApi:{type:"integer",format:"int64",description:"A bigint number",...i.openApi||{}}})}function zh(i={}){return _({type:"decimal",precision:i.precision??10,scale:i.scale??2,...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:Number.parseFloat(t)},openApi:{type:"number",format:"double",description:"A decimal number",...i.openApi||{}}})}function Gh(i={}){return _({type:"binary",...i,openApi:{type:"string",format:"binary",description:"Binary data",...i.openApi||{}}})}function Yh(i,t={}){return _({type:i,...t,openApi:{type:"string",enum:i,description:"An enum value",...t.openApi||{}}})}function Zh(i){return _({...i,prepare:t=>t&&Bf(i.key,t),serialize:t=>t&&kf(i.key,t)})}function Xh(i){return _({...i,prepare:t=>t&&Kf(i.publicKey,t),serialize:t=>t&&Qf(i.privateKey,t)})}function eg(i={}){return _({type:"boolean",...i,serialize:t=>!!t,prepare:t=>{if(t!=null)return !!t},openApi:{type:"boolean",description:"A boolean value",...i.openApi||{}}})}function tg(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"DATE_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"date",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"DATE_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},openApi:{type:"string",format:"date",description:"YYYY-MM-DD",...o.openApi||{}}})}function rg(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"ISO",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"datetime",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"ISO",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"YYYY-MM-DD HH:mm:ss",...s.openApi||{}}})}function ng(i={},t=false){let{timezone:e,withTimezone:r,autoUpdate:n=false,autoCreate:o=false,...s}=i,a=e??"UTC",l=r??e!==void 0,u=!!o,d=!!n,c=typeof o=="function"?"js":u?true:void 0,m=()=>new Date,p=()=>de(new Date,"TIMESTAMP",a),h=t?typeof o=="function"?o:p:typeof o=="function"?o:m,f=t?typeof n=="function"?n:p:typeof n=="function"?n:m;return _({type:"timestamp",...s,withTimezone:l,autoUpdate:d,autoCreate:c,prepare:t?q=>q?d?f():q:u?h():null:q=>q?d?f():q:u?h():null,serialize:t?q=>{if(q!==void 0)return q===null?null:q instanceof Date?de(q,"TIMESTAMP",a):String(q)}:q=>{if(q!==void 0)return q===null?null:q instanceof Date?q:new Date(q)},stringMode:t,openApi:{type:"string",format:"date-time",description:"Unix timestamp",...s.openApi||{}}})}function og(i={},t=false){let{timezone:e="UTC",autoUpdate:r=false,autoCreate:n=false,...o}=i,s=!!n,a=!!r,l=typeof n=="function"?"js":s?true:void 0,u=()=>new Date,d=()=>de(new Date,"TIME_ONLY",e),c=t?typeof n=="function"?n:d:typeof n=="function"?n:u,m=t?typeof r=="function"?r:d:typeof r=="function"?r:u;return _({type:"time",...o,autoUpdate:a,autoCreate:l,prepare:t?f=>f?a?m():f:s?c():null:f=>f?a?m():f:s?c():null,serialize:t?f=>{if(f!==void 0)return f===null?null:f instanceof Date?de(f,"TIME_ONLY",e):String(f)}:f=>{if(f!==void 0)return f===null?null:f instanceof Date?f:new Date(f)},stringMode:t,openApi:{type:"string",format:"time",description:"HH:mm:ss",...o.openApi||{}}})}function sg(i={}){return _({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t,openApi:{type:"object",description:"A JSON object",...i.openApi||{}}})}function ig(i,t={}){return _({...t,expression:i})}function Wf(i){try{return z.getMetadata(jr,i.prototype)||[]}catch{return []}}function jf(i){return z.getMetadata(Ql,i.prototype)||[]}function Ff(i){return (z.getMetadata(Ql,i.prototype)||[]).map(e=>{let{type:r,model:n,columnName:o,foreignKey:s}=e,a=C(s),l=n();switch(r){case "belongsTo":return new Xr(l,o,a);case "hasOne":return new tn(l,o,a);case "hasMany":return new en(l,o,a);case "manyToMany":if(!e.manyToManyOptions)throw new S("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let u=n();return new rn(u,o,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:C(e.manyToManyOptions.throughModel),leftForeignKey:C(e.manyToManyOptions.leftForeignKey),rightForeignKey:C(e.manyToManyOptions.rightForeignKey)});default:throw new S("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Uf(i){return z.getMetadata(Ct,i)||z.getMetadata(Ct,i.prototype)}function Vf(i){return z.getMetadata(Mf,i.prototype)||[]}function Jf(i){return z.getMetadata(xf,i.prototype)||[]}function Hf(i){return z.getMetadata(Of,i.prototype)||[]}var ye=class{};ye.columns=new WeakMap,ye.byName=new WeakMap,ye.byDatabaseName=new WeakMap;var Ae=class extends Ve{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");if(t&&"value"in t)return t.value;throw new Error(`Table name not set for model "${this.name}". Use defineModel() to create models.`)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Uf(this)}constructor(t){if(super(),t)for(let e in t)Object.assign(this,{[e]:t[e]});}static getColumns(){let t=ye.columns.get(this);return t||(t=Wf(this),ye.columns.set(this,t)),t}static getColumnsByName(){let t=ye.byName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.columnName,e])),ye.byName.set(this,t)),t}static getColumnsByDatabaseName(){let t=ye.byDatabaseName.get(this);return t||(t=new Map(this.getColumns().map(e=>[e.databaseName,e])),ye.byDatabaseName.set(this,t)),t}static getRelations(){return jf(this)}static getIndexes(){return Vf(this)}static getUniques(){return Jf(this)}static getChecks(){return Hf(this)}static async validate(t){var s,a;let e=this.getColumns(),r={},n=this.primaryKey,o=n&&t?.[n]!==void 0?"update":"insert";for(let l of e){if(l.expression)continue;let u=l.validate;if(!u)continue;let d=t?t[l.columnName]:void 0,c=Array.isArray(u)?u:[u];for(let m of c)try{let p=await m(d,{model:this,column:l.columnName,operation:o,data:t});if(!(p&&p.valid)){let h=p&&p.message||"Validation failed";(r[s=l.columnName]||(r[s]=[])).push(h);}}catch{(r[a=l.columnName]||(r[a]=[])).push("Validation error");}}if(Object.keys(r).length>0)throw new Pt(r);return {valid:true}}};Ae.zodEngine=null,Ae.softDeleteColumn="deletedAt",Ae.softDeleteValue=bt();var Mt=class extends N{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var U=class extends N{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var re=class extends N{constructor(e,r=[],n,o=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=n,this.disableReturning=o;}};var Ce=class extends N{constructor(e,r,n,o="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=n,this.mode=o,this.returning=s;}};var xt=class extends N{constructor(e=[],r="inserted"){super("returning");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="returning";this.file="returning";this.columns=e,this.prefix=r;}};var Ee=class extends N{constructor(e,r=[],n=[],o=false){super("update",o);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=n;}};var M=class extends N{constructor(e,r,n=false,o,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=n,this.operator=o,this.value=s;}};var $e=class extends N{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var j=class extends M{constructor(e,r,n=false,o,s,a=false,l,u){super(e,r,n,"=",s,a);this.file="where_json";this.jsonOperator=o,this.value=s,this.path=l,this.comparisonOperator=u;}};var Re=class extends N{constructor(e,r,n,o="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=n,this.chainsWith=` ${o}`;}};var zf;zf=Symbol.toStringTag;var G=class{constructor(t,e,r,n){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=n;this[zf]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}toSql(){return this.toSqlFn()}unWrap(){return this.unWrapFn()}};var ag=(i,t,e,r,n,o=false)=>{let s=Object.create(t.prototype);for(let a of Object.keys(i)){let l=i[a],u=e.get(a),d=a;u||(u=r.get(a),u&&(d=u.columnName));let c=u!==void 0,m=o?true:n?n.has(d):true;if(c){if(!m)continue;if(l===null){s[d]=null;continue}if(u?.serialize){let p=u.serialize(l);if(p!==null&&typeof p?.then=="function")throw new Error(`hysteria-orm: column "${d}" on model "${t.name}" has an async serialize function, but serializers must be synchronous. Move async work to prepare or a getter.`);s[d]=p;continue}s[d]=l;continue}(!o||n&&n.has(d))&&(s[d]=l);}if(n)for(let a of n)a in s||(s[a]=null);return s},he=(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),n=t.getColumnsByDatabaseName(),o=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let p=u.match(/\s+as\s+(.+)$/i);p&&s.push(p[1].trim());continue}let c=u;if(c.includes(".")&&(c=c.split(".").pop()),c==="*")continue;let m=r.get(c)?.columnName??c;s.push(m);}let a=s.length?new Set(s):null,l=i.map(u=>ag(u,t,r,n,a,o));return l.length===1?l[0]:l};var Ft=class{constructor(t){this.observers=t??[];}add(t){this.observers.push(t);}async notifyBefore(t){for(let e of this.observers)e?.onBeforeQuery&&await e.onBeforeQuery(t);}async notifyAfter(t,e){for(let r of this.observers)r?.onAfterQuery&&(t.result??(t.result=e),await r.onAfterQuery(t));}async notifyError(t){for(let e of this.observers)e?.onQueryError&&await e.onQueryError(t);}},Gf=i=>{if(!i)return "OTHER";let t=i.trim().toUpperCase();return t.startsWith("SELECT")?"SELECT":t.startsWith("INSERT")?"INSERT":t.startsWith("UPDATE")?"UPDATE":t.startsWith("DELETE")?"DELETE":"OTHER"};var nn=ie();function Jl(i){let t=nn.timing.now()-i;return Math.round(t*100)/100}var J=async(i,t,e,r,n="rows",o)=>{await e.ensureConnected();let s={id:nn.crypto.randomUUID(),sql:i,params:t,model:void 0,operation:Gf(i),timestamp:nn.timing.now()};try{let u=e.observerChain;u&&typeof u.notifyBefore=="function"&&await u.notifyBefore(s);}catch{}let a=nn.timing.now(),l=u=>{o?.shouldNotLog||ct(i,e.logs,t,e.inputDetails.queryFormatOptions,r,u);};try{let u=e.driverAdapter;if(!u)throw new S("ExecSql","CONNECTION_NOT_ESTABLISHED");let d=o?.timeout,c=d?new AbortController:void 0,m,p=lg(()=>u.execute(i,t,{returning:n,sqlLiteOptions:o?.sqlLiteOptions,signal:c?.signal,connection:e.sqlConnection}),e.inputDetails.connectionPolicies?.retry,e.logs),h;try{d&&c?(h=await Promise.race([p,new Promise((f,T)=>{m=setTimeout(()=>{let w=new S("ExecSql::timeout","QUERY_TIMEOUT",new Error(`Query exceeded the ${d.ms}ms timeout`));d.cancel&&c.abort(w),T(w);},d.ms);})]),p.catch(()=>{})):h=await p;}finally{m&&clearTimeout(m);}try{let f=Jl(a),T=e.observerChain;if(T&&typeof T.notifyAfter=="function"){let w={...s,duration:f,result:h};await T.notifyAfter(w);}}catch{}return l(Jl(a)),u.extract(h,n)}catch(u){throw l(Jl(a)),u}},on=async(i,t,e,r={},n)=>{let o=e.driverAdapter;if(!o)throw new S("ExecSqlStreaming","CONNECTION_NOT_ESTABLISHED");return await o.stream(i,t,{...r,connection:e.sqlConnection??void 0},{onData:n.onData})};async function lg(i,t={maxRetries:0,delay:0},e=false){let r=0,n=t.maxRetries||0,o=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<n)return r++,Nu(`Retrying sql in ${o}ms (attempt ${r}/${n})`,"info",e),await new Promise(l=>setTimeout(l,o)),s();throw a}}return s()}var Y=class extends N{constructor(e,r,n,o,s){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=n,this.isRawValue=o??false,this.distinct=s;}};var Ut=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Ff(t),this.modelRelationsMap=new Map(this.modelRelations.map(n=>[n.columnName,n]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new S("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function sn(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}var Ot=i=>typeof i=="number"?i:parseFloat(i);var X=class extends N{constructor(e,r,n=false,o,s,a=false,l,u){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=` ${r}`,this.isNegated=n,this.operator=o,this.value=s,this.subquery=l,this.group=u;}};var an=class extends N{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var ln=class extends N{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Je=class extends N{constructor(e,r,n,o="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=n,this.jsonOperator=o,this.isRawValue=s;}};var se=class extends N{constructor(e,r,n,o="inner",s,a=false,l){super(`${o} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=n,this.type=o,this.on=s,this.additionalConditions=l;}};var Vt=class extends N{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var un=class extends N{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var dn=class extends N{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Jt=class extends N{constructor(e,r="asc",n=false){super("order by",n);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var mn=class mn{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs,typeof t.getColumns=="function"?(this.modelColumns=t.getColumns(),this.modelColumnsMap=t.getColumnsByName?.()??new Map(this.modelColumns.map(r=>[r.columnName,r]))):(this.modelColumns=[],this.modelColumnsMap=mn.EMPTY_MAP);}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new Vt(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Vt(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Jt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Jt(t,"asc",true)),this}limit(t){return typeof t!="number"&&g.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new un(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new dn(t),this}};mn.EMPTY_MAP=new Map;var cn=mn;var nt=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",false,n,o)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",false,n,o)),this}whereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}andWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"and",true,n,o)),this}orWhereNot(t,e,r){let n="=",o;return typeof e=="string"&&r!==void 0?(n=e,o=r):(o=e,n="="),this.whereNodes.push(new M(t,"or",true,n,o)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new M(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new M(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new M(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new M(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new M(t,"and",false,"in",e)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",false,"in",e)),this):(this.whereNodes.push(new M("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"and",true,"in",e)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new M(t,"or",true,"in",e)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new M(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new M(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new M(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new M(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new $e(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new $e(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new M(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new M(t,"or",true,"=",e??[],true)),this}};var pn=class extends cn{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new se(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new se(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new se(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new se(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new se(t,"","","cross",{operator:"="},true)),this}crossJoin(t,e){let r=typeof t=="string"?t:t.table;return this.joinNodes.push(new se(e?`${r} as ${e}`:r,"","","cross",{operator:"="})),this}using(...t){let e=this.joinNodes[this.joinNodes.length-1];if(!e||!t.length||e.isRawValue||e.type==="cross"||e.type==="natural")throw new S("JoinQueryBuilder::using","USING_REQUIRES_JOIN");return e.using=t.map(r=>String(r)),this}naturalJoinRaw(t){return this.joinNodes.push(new se(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,n,o){if(e===void 0)return this.join(typeof t=="string"?t:t.table);let s=r,a=n,l=typeof n=="function"?n:o;if(!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","inner",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","left",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,n,o){if(e===void 0)return this.joinNodes.push(new se(typeof t=="string"?t:t.table,"","","right",{operator:"="})),this;let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,n,o){let s=r,a="=",l;if(typeof n=="function"?l=n:typeof n=="string"&&(a=n,l=o),!s){if(!this.model.primaryKey)throw new S("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new nt(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new se(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var fn=class extends pn{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[a,l]=r;this.modelSelectedColumns.push(l);let u=this.resolveComputedColumn(a);if(u){this.selectNodes.push(new Y(`(${u.expression}) as ${l}`,void 0,void 0,true));return}let d=H(a,this.model.databaseCaseConvention);this.selectNodes.push(new Y(d,l));return}let n=r;this.modelSelectedColumns.push(n);let o=this.resolveComputedColumn(n);if(o){this.selectNodes.push(new Y(`(${o.expression}) as ${o.alias}`,void 0,void 0,true));return}let s=H(n,this.model.databaseCaseConvention);this.selectNodes.push(new Y(s));}),this}selectRaw(e){return this.selectNodes.push(new Y(e,void 0,void 0,true)),this}selectFunc(e,r,n){return this.selectNodes.push(new Y(r,n,e)),this}countDistinct(e,r){return this.selectNodes.push(new Y(e,r,"count",false,true)),this}sumDistinct(e,r){return this.selectNodes.push(new Y(e,r,"sum",false,true)),this}avgDistinct(e,r){return this.selectNodes.push(new Y(e,r,"avg",false,true)),this}rank(e,r={}){return this.pushWindow("rank",e,r)}denseRank(e,r={}){return this.pushWindow("dense_rank",e,r)}rowNumber(e,r={}){return this.pushWindow("row_number",e,r)}pushWindow(e,r,n){return this.selectNodes.push(new Y(new Fr(e,Df(n.partitionBy),Af(n.orderBy)),r)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}resolveComputedColumn(e){let r=this.model.getColumnsByName?.();if(!r||r.size===0)return;let n=e.includes(".")?e.split(".").pop():e,o=r.get(n);if(o?.expression)return {expression:o.expression,alias:o.databaseName||n}}clearFrom(){return this.fromNode=new U(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}table(e){return this.fromNode=new U(e),this}distinct(){return this.distinctNode=new an,this}distinctOn(...e){return this.distinctOnNode=new ln(e),this}selectJson(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract")),this}selectJsonText(e,r,n){return this.selectNodes.push(new Je(e,r,n,"extract_text")),this}selectJsonArrayLength(e,r,n){return this.selectNodes.push(new Je(e,r,n,"array_length")),this}selectJsonKeys(e,r,n){return this.selectNodes.push(new Je(e,r,n,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Je(e,"",r,"raw",true)),this}};var yn=class extends fn{constructor(e,r,n=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=n;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,n){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&n===void 0?this.andWhereSubQuery(e,"in",r):r instanceof B&&n===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function")?this.andWhereSubQuery(e,r,n):this.andWhere(e,r,n)}andWhere(e,r,n){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",false,o,s)),this}orWhere(e,r,n){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",false,o,s)),this}whereColumn(e,r,n){return this.andWhereColumn(e,r,n)}andWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"and",false,o,new x(s))),this}orWhereColumn(e,r,n){let o="=",s;return n!==void 0?(o=r,s=n):s=r,this.whereNodes.push(new M(e,"or",false,o,new x(s))),this}whereNotColumn(e,r,n){return this.andWhereNotColumn(e,r,n)}andWhereNotColumn(e,r,n){return this.pushNotColumnWhere("and",e,r,n)}orWhereNotColumn(e,r,n){return this.pushNotColumnWhere("or",e,r,n)}pushNotColumnWhere(e,r,n,o){let s="!=",a=false,l;return o!==void 0?(s=n,l=o,a=true):l=n,this.whereNodes.push(new M(r,e,a,s,new x(l))),this}whereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}andWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.andWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"and",true,o,s)),this}orWhereNot(e,r,n){if(typeof r=="function"&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof B&&n===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&n!==void 0&&(n instanceof B||typeof n=="function"))return this.orWhereSubQuery(e,r,n);let o="=",s;return typeof r=="string"&&n!==void 0&&!(n instanceof B)&&typeof n!="function"?(o=r,s=n):(s=r,o="="),this.whereNodes.push(new M(e,"or",true,o,s)),this}whereBetween(e,r,n){return this.andWhereBetween(e,r,n)}andWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"and",false,"between",[r,n])),this}orWhereBetween(e,r,n){return this.whereNodes.push(new M(e,"or",false,"between",[r,n])),this}whereNotBetween(e,r,n){return this.andWhereNotBetween(e,r,n)}andWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"and",true,"between",[r,n])),this}orWhereNotBetween(e,r,n){return this.whereNodes.push(new M(e,"or",true,"between",[r,n])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"and",false,"in",r)),this):(this.whereNodes.push(new M("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",false,"in",r)),this):(this.whereNodes.push(new M("false","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"in",r)}whereNotIn(e,r){return this.andWhereNotIn(e,r)}andWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"and",true,"in",r)),this):(this.whereNodes.push(new M("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new M(e,"or",true,"in",r)),this):(this.whereNodes.push(new M("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new M(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new M(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new M(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new M(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"and",false,n?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new M(e,"or",false,n?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"and",true,n?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let n=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new M(e,"or",true,n?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof B?e:new B(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new Re("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new M(e,"or",false,"=",r,true)),this}having(e,r,n){return this.andHaving(e,r,n)}andHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"and",false,o,s)),this}orHaving(e,r,n){let o="=",s;return typeof r=="string"&&n?(o=r,s=n):(s=r,o="="),this.havingNodes.push(new X(e,"or",false,o,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new X(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new X(e,"or",false,"=",[],true)),this}havingNull(e){return this.andHavingNull(e)}andHavingNull(e){return this.havingNodes.push(new X(e,"and",false,"is null",void 0)),this}orHavingNull(e){return this.havingNodes.push(new X(e,"or",false,"is null",void 0)),this}havingNotNull(e){return this.andHavingNotNull(e)}andHavingNotNull(e){return this.havingNodes.push(new X(e,"and",false,"is not null",void 0)),this}orHavingNotNull(e){return this.havingNodes.push(new X(e,"or",false,"is not null",void 0)),this}havingIn(e,r){return this.andHavingIn(e,r)}andHavingIn(e,r){return this.pushHavingIn("and",e,r,false)}orHavingIn(e,r){return this.pushHavingIn("or",e,r,false)}havingNotIn(e,r){return this.andHavingNotIn(e,r)}andHavingNotIn(e,r){return this.pushHavingIn("and",e,r,true)}orHavingNotIn(e,r){return this.pushHavingIn("or",e,r,true)}havingBetween(e,r){return this.andHavingBetween(e,r)}andHavingBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"between",r)),this}orHavingBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"between",r)),this}havingNotBetween(e,r){return this.andHavingNotBetween(e,r)}andHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"and",false,"not between",r)),this}orHavingNotBetween(e,r){return this.havingNodes.push(new X(e,"or",false,"not between",r)),this}havingExists(e){return this.andHavingExists(e)}andHavingExists(e){return this.pushHavingExists("and",e,false)}orHavingExists(e){return this.pushHavingExists("or",e,false)}havingNotExists(e){return this.andHavingNotExists(e)}andHavingNotExists(e){return this.pushHavingExists("and",e,true)}orHavingNotExists(e){return this.pushHavingExists("or",e,true)}havingWrapped(e){return this.andHavingWrapped(e)}andHavingWrapped(e){return this.pushHavingGroup("and",e)}orHavingWrapped(e){return this.pushHavingGroup("or",e)}pushHavingIn(e,r,n,o){let s=o?"not in":"in";if(Array.isArray(n))return this.havingNodes.push(new X(r,e,false,s,n)),this;let a=this.buildSubQuery(n);return this.havingNodes.push(new X(r,e,false,s,[],false,a.extractQueryNodes())),this}pushHavingExists(e,r,n){let o=r instanceof B?r:new B(this.model,this.sqlDataSource);return o.isNestedCondition=true,typeof r=="function"&&r(o),this.havingNodes.push(new X("",e,false,n?"not exists":"exists",[],false,o.extractQueryNodes())),this}pushHavingGroup(e,r){let n=new B(this.model,this.sqlDataSource);return n.isNestedCondition=true,r(n),this.havingNodes.push(new X("",e,false,"=",[],false,void 0,n.havingNodes)),this}buildSubQuery(e){if(e instanceof B)return e;let r=new B(this.model,this.sqlDataSource),n=e(r);return n!=null&&"extractQueryNodes"in n?n:r}andWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,n){let o=this.buildSubQuery(n);return this.whereNodes.push(new Re(e,r,o.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"and");return this.whereNodes.push(n),this}orWhereGroup(e){let r=new B(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let n=new $e(r.whereNodes,"or");return this.whereNodes.push(n),this}};var hn=class extends yn{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new j(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new j(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new j(t,"or",false,"raw",e)),this}whereJsonObject(t,e){return this.andWhereJsonObject(t,e)}andWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"and",false,"=",e)),this}orWhereJsonObject(t,e){return this.whereNodes.push(new j(t,"or",false,"=",e)),this}whereNotJsonObject(t,e){return this.andWhereNotJsonObject(t,e)}andWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"and",true,"=",e)),this}orWhereNotJsonObject(t,e){return this.whereNodes.push(new j(t,"or",true,"=",e)),this}whereJsonPath(t,e,r,n){return this.andWhereJsonPath(t,e,r,n)}andWhereJsonPath(t,e,r,n){return this.pushJsonPath("and",t,e,r,n,false),this}orWhereJsonPath(t,e,r,n){return this.pushJsonPath("or",t,e,r,n,false),this}whereJsonSupersetOf(t,e){return this.andWhereJsonSupersetOf(t,e)}andWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"contains",e)),this}orWhereJsonSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"contains",e)),this}whereJsonNotSupersetOf(t,e){return this.andWhereJsonNotSupersetOf(t,e)}andWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"contains",e)),this}orWhereJsonNotSupersetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"contains",e)),this}whereJsonSubsetOf(t,e){return this.andWhereJsonSubsetOf(t,e)}andWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",false,"subset",e)),this}orWhereJsonSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",false,"subset",e)),this}whereJsonNotSubsetOf(t,e){return this.andWhereJsonNotSubsetOf(t,e)}andWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"and",true,"subset",e)),this}orWhereJsonNotSubsetOf(t,e){return this.whereNodes.push(new j(t,"or",true,"subset",e)),this}whereJsonHasNone(t,e){return this.andWhereJsonHasNone(t,e)}andWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"and",false,"has none",e)),this}orWhereJsonHasNone(t,e){return this.whereNodes.push(new j(t,"or",false,"has none",e)),this}pushJsonPath(t,e,r,n,o,s){let a=new j(e,t,s,"path",o,false,r,n);this.whereNodes.push(a);}};var B=class i extends hn{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.returningNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.comments=[],this.hints=[],this.astParser=new b(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new y(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,n]=e;if(typeof r=="function"){let o=new i(this.model,this.sqlDataSource),s=r(o),a=s!=null&&"extractQueryNodes"in s?s:o;return this.selectNodes.push(new Y(a.extractQueryNodes(),n)),this}return this.selectNodes.push(new Y(r.extractQueryNodes(),n)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}countDistinct(e,r){return super.countDistinct(e,r),this}sumDistinct(e,r){return super.sumDistinct(e,r),this}avgDistinct(e,r){return super.avgDistinct(e,r),this}rank(e,r){return super.rank(e,r),this}denseRank(e,r){return super.denseRank(e,r),this}rowNumber(e,r){return super.rowNumber(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",n=>J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(n=>n[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new S("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:n}=this.unWrap();return this.execSqlWithSlaveHandling("read",async o=>await on(r,n,o,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;r+=n.length,yield n;}}async paginateWithCursor(e,r){if(!this.orderByNodes.length)throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_REQUIRED");let n=this.orderByNodes;if(n.some(m=>m.isRawValue))throw new S(this.model.name+"::paginateWithCursor","ORDER_BY_RAW_NOT_SUPPORTED");let o=n.map(m=>m.column),s=n[0].direction==="desc"?"<":">";if(r){let m=Array.isArray(r.value)?r.value:[r.value];this.andWhere(p=>{for(let h=0;h<o.length;h++){let f=h;p.orWhere(T=>{for(let w=0;w<f;w++)T.where(o[w],"=",m[w]);T.where(o[f],s,m[f]);});}});}this.limit(e+1);let a=await this.many(),l=a.length>e,u=l?a.slice(0,e):a,d=u[u.length-1],c=o.map(m=>m.includes(".")?m.slice(m.lastIndexOf(".")+1):m);return {data:u,hasMore:l,nextCursor:d?{key:c.length===1?c[0]:c,value:c.length===1?d[c[0]]:c.map(m=>d[m])}:null}}lockForUpdate(e={}){return this.lockQueryNodes.push(new Xe("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Xe("for_share",e.skipLocked,e.noWait)),this}forNoKeyUpdate(e={}){return this.assertPgLockStrength("forNoKeyUpdate","FOR NO KEY UPDATE"),this.lockQueryNodes.push(new Xe("for_no_key_update",e.skipLocked,e.noWait)),this}forKeyShare(e={}){return this.assertPgLockStrength("forKeyShare","FOR KEY SHARE"),this.lockQueryNodes.push(new Xe("for_key_share",e.skipLocked,e.noWait)),this}assertPgLockStrength(e,r){if(this.dbType!=="postgres")throw new S(`QueryBuilder::${e}`,`LOCK_STRENGTH_NOT_SUPPORTED_IN_${this.dbType.toUpperCase()}`,new Error(`${r} is only supported by postgres`))}timeout(e,r={}){return this.queryTimeout={ms:e,cancel:r.cancel??false},this}comment(e){return this.assertValidSqlComment(e),this.comments.push(e),this}hintComment(e){this.assertValidSqlComment(e);let r=e.slice(3,-2).trim(),n=this.hints[0];return this.hints=[n?`${n.slice(0,-2).trimEnd()} ${r} */`:`/*+ ${r} */`],this}clearComment(){return this.comments=[],this}clearHintComment(){return this.hints=[],this}assertValidSqlComment(e){let r=()=>{throw new S("QueryBuilder::comment","INVALID_SQL_COMMENT")};(!e.trim().length||e.includes("?"))&&r();let n=(this.dbType==="mysql"||this.dbType==="mariadb")&&e.startsWith("#");if(e.startsWith("--")||n){/[\r\n]/.test(e)&&r();return}if(e.startsWith("/*")&&e.endsWith("*/")&&e.length>=4){let o=e.slice(2,-2);(o.includes("/*")||o.includes("*/"))&&r();return}r();}union(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new Ie(e,true)),this;let n=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new Ie(n,true)),this}intersect(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"intersect")),this}except(e){return this.unionNodes.push(new Ie(this.resolveSetOperationNodes(e),false,"except")),this}resolveSetOperationNodes(e){return typeof e=="string"?e:(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes()}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.buildCountQuery(e);let r=await this.one();return r?Ot(r.total):0}needsDerivedTableCount(){return this.groupByNodes.length>0||this.havingNodes.length>0||this.distinctNode!==null||this.distinctOnNode!==null}buildCountQuery(e="*"){if(!this.needsDerivedTableCount()){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);return}this.clearOrderBy(),this.clearLimit(),this.clearOffset();let r=this.extractQueryNodes();this.withNodes=[],this.distinctNode=null,this.distinctOnNode=null,this.clearSelect(),this.fromNode=new U(r,"g"),this.joinNodes=[],this.whereNodes=[],this.groupByNodes=[],this.havingNodes=[],this.lockQueryNodes=[],this.unionNodes=[],this.comments=[],this.hints=[],this.selectRaw(`count(${e}) as total`);}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?Ot(r.total):0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?Ot(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?Ot(r.total):0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?Ot(r.total):0}async columnInfo(e){let r=typeof this.fromNode.table=="string"?this.fromNode.table:this.model.table,o=await(await this.getSqlDataSource("read")).getTableInfo(r);return e===void 0?o:o.find(s=>s.name===e)}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new S("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let n=new i(this.model,this.sqlDataSource),o=e(n),a=(o!=null&&"extractQueryNodes"in o?o:n).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}withSchema(e){return this.schemaName=e,this}fromRaw(e,r=[]){return this.fromNode=new U(new x(e,r)),this}with(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("materialized",e,s.extractQueryNodes())),this}withNotMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new S("QueryBuilder::withNotMaterialized","NOT_MATERIALIZED_CTE_NOT_SUPPORTED",new Error("NOT MATERIALIZED CTE is only supported by postgres"));let n=new i(this.model,this.sqlDataSource),o=r(n),s=o!=null&&"extractQueryNodes"in o?o:n;return this.withNodes.push(new et("not materialized",e,s.extractQueryNodes())),this}insert(e,r){let n=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,[this.interpreterUtils.stripComputedFromData(n)],r,o),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),l=Object.fromEntries(s.map((p,h)=>[p,a[h]]));this.insertNode=new re(this.fromNode,[l],r,o);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!o)return Array.isArray(m)&&m.length?m[0]:m})}insertMany(e,r){let n=e.map(s=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(s).map(a=>[a,s[a]])))),o=!r||r.length===0;return this.insertNode=new re(this.fromNode,n,r,o),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return o?void 0:[];let s=await Promise.all(e.map(async c=>{let{columns:m,values:p}=this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert",this.dbType);return Object.fromEntries(m.map((h,f)=>[h,p[f]]))}));this.insertNode=new re(this.fromNode,s,r,o);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await J(a,l,u,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!o)return d})}upsert(e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(Object.keys(e)),s=Object.keys(r),a=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(e).map(l=>[l,e[l]])));return this.insertNode=new re(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert",this.dbType),d=Object.fromEntries(l.map((f,T)=>[f,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,o,n,[e]);let{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),[d],void 0,true),new Ce(this.model.table,s,o,n.updateOnConflict??true?"update":"ignore",n.returning)]),p=await this.getSqlDataSource("write"),h=await J(c,m,p,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(h)?h:[h]})}upsertMany(e,r,n,o={updateOnConflict:true}){let s=this.interpreterUtils.filterComputedColumns(r),a=n.map(l=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(l).map(u=>[u,l[u]]))));return this.insertNode=new re(new U(this.model.table),a,void 0,true),this.onDuplicateNode=new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let l=[];if(await Promise.all(n.map(async p=>{let{columns:h,values:f}=this.interpreterUtils.prepareColumns(Object.keys(p),Object.values(p),"insert",this.dbType),T=Object.fromEntries(h.map((w,q)=>[w,f[q]]));l.push(T);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(l,e,s,o,n);let{sql:u,bindings:d}=this.astParser.parse([new re(new U(this.model.table),l,void 0,true),new Ce(this.model.table,e,s,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await this.getSqlDataSource("write"),m=await J(u,d,c,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,n,o,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=K=>this.interpreterUtils.formatStringColumn("mssql",K),d=[],c=e.map(K=>`select ${a.map(v=>(d.push(K[v]),`@${d.length}`)).join(", ")}`),m=a.map(u).join(", "),p=c.join(" union all "),h=r.map(K=>`target.${u(K)} = source.${u(K)}`).join(" and "),f=n.filter(K=>!r.includes(K)).map(K=>`target.${u(K)} = source.${u(K)}`).join(", "),T=a.map(u).join(", "),w=a.map(K=>`source.${u(K)}`).join(", "),q=o.returning&&o.returning.length?o.returning.map(K=>`inserted.${u(K)}`).join(", "):a.map(K=>`inserted.${u(K)}`).join(", "),R=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",$=`merge into ${l} as target using (${p}) as source (${m}) on ${h} ${R} when not matched then insert (${T}) values (${w}) output ${q};`,A=await this.getSqlDataSource("write"),O=await J($,d,A,this.dbType,"rows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(O)?O:[O]}update(e,r){let n=this.interpreterUtils.stripComputedFromData(e),o=Object.keys(n),s=Object.values(n);this.updateNode=new Ee(this.fromNode,o,s),this.returningNode=this.buildReturningNode("update",r);let a=this.returningNode!==null;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=this.interpreterUtils.prepareColumns(o,s,"update",this.dbType);this.updateNode=new Ee(this.fromNode,l,u);let{sql:d,bindings:c}=this.astParser.parse(this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes])),m=await this.getSqlDataSource("write");return J(d,c,m,this.dbType,a?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:a?"fetch":"affectedRows"}})})}buildReturningNode(e,r){return !r?.length||!this.interpreterUtils.dialectEmitsReturning(this.dbType)?null:new xt(r,e==="delete"?"deleted":"inserted")}withReturningNode(e){if(!this.returningNode)return e;if(this.dbType==="mssql"){let[r,...n]=e;return [r,this.returningNode,...n]}return [...e,this.returningNode]}truncate(){return this.truncateNode=new qt(this.fromNode),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),n=await this.getSqlDataSource("write");await J(e,r,n,this.dbType,"rows",{timeout:this.queryTimeout});})}delete(e){this.deleteNode=new Mt(this.fromNode),this.returningNode=this.buildReturningNode("delete",e);let r=this.returningNode!==null;return new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:n,bindings:o}=this.astParser.parse(this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes])),s=await this.getSqlDataSource("write");return J(n,o,s,this.dbType,r?"rows":"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:n=bt()}=e||{};return this.updateNode=new Ee(this.fromNode,[r],[n]),new G(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:o,values:s}=this.interpreterUtils.prepareColumns([r],[n],"update",this.dbType);this.updateNode=new Ee(this.fromNode,o,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return J(a,l,u,this.dbType,"affectedRows",{timeout:this.queryTimeout,sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return it(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),n=lt(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${n}`:n,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new Y("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes());return {sql:this.withQuery?`${this.withQuery} ${e}`:e,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=W(this.modelSelectedColumns),e.distinctNode=W(this.distinctNode),e.distinctOnNode=W(this.distinctOnNode),e.selectNodes=W(this.selectNodes),e.withQuery=W(this.withQuery),e.joinNodes=W(this.joinNodes),e.whereNodes=W(this.whereNodes),e.groupByNodes=W(this.groupByNodes),e.havingNodes=W(this.havingNodes),e.orderByNodes=W(this.orderByNodes),e.lockQueryNodes=W(this.lockQueryNodes),e.unionNodes=W(this.unionNodes),e.withNodes=W(this.withNodes),e.comments=[...this.comments],e.hints=[...this.hints],e.schemaName=this.schemaName,e.fromNode=W(this.fromNode),e.limitNode=W(this.limitNode),e.offsetNode=W(this.offsetNode),e.returningNode=W(this.returningNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){if(this.selectNodes.length||(this.selectNodes=[new Y("*")]),this.schemaName){this.fromNode&&typeof this.fromNode.table=="string"&&(this.fromNode.schema=this.schemaName);for(let n of this.joinNodes)n.schema=this.schemaName;}if(this.insertNode)return [this.insertNode,this.onDuplicateNode].filter(Boolean);if(this.updateNode)return this.withReturningNode([this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.deleteNode)return this.withReturningNode([this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode]).filter(Boolean);if(this.truncateNode)return [this.truncateNode];let e=this.comments.map(n=>new Lt(n)),r=this.hints.length?[new Lt(this.hints.join(" "),true)]:[];return [...this.withNodes,...e,this.distinctNode,this.distinctOnNode,...this.selectNodes,...r,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let n=await e(),o=await r();return [n,o]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let n=await this.getSqlDataSource(e);if(!(n!==this.sqlDataSource))return r(n);try{return await r(n)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:n.host,port:n.port,username:n.username,password:n.password,database:n.database,type:n.getDbType()}),await r(this.sqlDataSource);throw a}}};function Yf(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:ug(i)}function ug(i){let{parentCount:t,relationType:e,hasLimitOffset:r}=i;return r&&(e==="hasMany"||e==="manyToMany")?"batched":t===1?"join":e==="manyToMany"?typeof t=="number"&&t<=10?"join":"batched":typeof t=="number"&&t<10?"join":"batched"}var Hl=ie(),ot=class i extends B{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Ut(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[n,o]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(n,o.columnName);}expandModelSelectColumns(){let e=this.selectNodes;if(!e.length){if(this.joinNodes.length)return;for(let[,r]of this.modelColumnsMap)r.expression||e.push(new Y(r.databaseName,r.columnName));return}for(let r of e){if(r.isRawValue||r.alias!==void 0||typeof r.column!="string"||r.column.includes(".")||r.column==="*")continue;let n=this.modelColumnsMap.get(r.column);!n||n.expression||(r.alias=n.columnName);}}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(e){let r=await this.one();if(!r)throw new S(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(){await this.model.beforeFetch?.(this),this.expandModelSelectColumns();let r=await super.many();if(!r.length)return [];let n=he(r,this.model,this.modelSelectedColumns);if(!n)return [];let o=Array.isArray(n)?n:[n];return this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(o),o}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e){let r=0;for(;;){let n=await this.limit(e).offset(r).many();if(!n.length)break;yield n,r+=n.length;}}async stream(e={}){await this.model.beforeFetch?.(this),this.expandModelSelectColumns();let{sql:r,bindings:n}=this.unWrap(),o=await this.getSqlDataSource("read");return await on(r,n,o,e,{onData:async(a,l)=>{let u=he([l],this.model,this.modelSelectedColumns);u&&(this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}async paginateWithCursor(e,r){return super.paginateWithCursor(e,r)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{returning:r.returning})}upsert(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return o.upsertMany(s,a,[l],{updateOnConflict:n.updateOnConflict??true,returning:n.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,n={updateOnConflict:true}){let o=this.getModelManager(n.trx),s=r.length>0?Object.keys(r[0]):[];return o.upsertMany(e,s,r,{updateOnConflict:n.updateOnConflict??true,returning:n.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource.getTransactionBoundSqlDataSource()??this.sqlDataSource;return new st(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,n){return this.getModelManager(n?.trx).updateRecord(e,r,n)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let n=this.model.primaryKey;if(!n)throw new S(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let o=e[n],s=o?{[n]:o}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,n){let{column:o=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[o]:s};return this.getModelManager(n?.trx).updateRecord(e,a,{returning:n?.returning})}async firstOrInsert(e,r,n){let o=this.getModelManager(n?.trx),s=await o.findOne({where:e});if(s)return s;let a={...e,...r};return o.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,n,o,s={}){if(Array.isArray(n)||(n=[n]),!n.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new S(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=H(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=H(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=n.map((p,h)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...o?o(p,h):{}}));class c extends Ae{static get table(){return a.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await new st(c,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let n=r.returning,o=super.update(e,n);return new G(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>{if(!n||!this.returningNode)return o;let s=await o;return he(s,this.model,n)})}softDelete(e={}){let r=super.softDelete(e);return new G(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>r)}delete(e={}){let r=e.returning,n=super.delete(r);return new G(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>{if(!r||!this.returningNode)return n;let o=await n;return he(o,this.model,r)})}async getCount(e="*"){this.buildCountQuery(e);let r=await this.one();return r?+r.total:0}async getMax(e){this.clearForFunctions(),this.selectFunc("max",e,"total");let r=await this.one();return r?+r.total:0}async getMin(e){this.clearForFunctions(),this.selectFunc("min",e,"total");let r=await this.one();return r?+r.total:0}async getAvg(e){this.clearForFunctions(),this.selectFunc("avg",e,"total");let r=await this.one();return r?+r.total:0}async getSum(e){this.clearForFunctions(),this.selectFunc("sum",e,"total");let r=await this.one();return r?+r.total:0}async paginate(e,r){let n=this.clone(),o=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>o.many(),()=>n.getCount("*"));return {paginationMetadata:sn(e,r,a),data:s}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof B)&&typeof e[1]=="string"){let[r,n]=e;return super.select(r,n),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,n){return super.selectFunc(e,r,n),this}countDistinct(e,r){return super.countDistinct(e,r),this}sumDistinct(e,r){return super.sumDistinct(e,r),this}avgDistinct(e,r){return super.avgDistinct(e,r),this}rank(e,r){return super.rank(e,r),this}denseRank(e,r){return super.denseRank(e,r),this}rowNumber(e,r){return super.rowNumber(e,r),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,n){return super.selectJson(e,r,n),this}selectJsonText(e,r,n){return super.selectJsonText(e,r,n),this}selectJsonArrayLength(e,r,n){return super.selectJsonArrayLength(e,r,n),this}selectJsonKeys(e,r,n){return super.selectJsonKeys(e,r,n),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,n){let o,s={strategy:"auto"};typeof r=="function"?(o=r,n&&(s=n)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,o?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,n){return this.andHavingRelated(e,r,n)}andHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.whereExists(d),this}orHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.orWhereExists(d),this}notHavingRelated(e,r,n){return this.andNotHavingRelated(e,r,n)}andNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.whereNotExists(d),this}orNotHavingRelated(e,r,n){let o,s,a;typeof r=="function"?a=r:typeof r=="string"&&n!==void 0?(s=r,o=n):r!==void 0&&(o=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,o),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=W(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let n=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,n);}));}async processRelationsWithStrategy(e){let r=e.length,n=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),o=async s=>{let a=Yf({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of n)await o(s);return}await Promise.all(n.map(o));}async loadRelationViaJoin(e,r){let n=e.relation,o=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,n,o).many();this.mapJoinedResultsToModels(a,r,n,o);}buildJoinQuery(e,r,n){let o=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)o.selectNodes.push(W(s));else for(let[s,a]of this.model.getColumnsByDatabaseName())a.expression||o.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=W(s);this.qualifyWhereNodeColumns(a,this.model.table),o.whereNodes.push(a);}for(let s of this.groupByNodes)o.groupByNodes.push(W(s));for(let s of this.orderByNodes)o.orderByNodes.push(W(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(o.limitNode=W(this.limitNode)),this.offsetNode&&(o.offsetNode=W(this.offsetNode))),r.type){case "hasOne":case "hasMany":o.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":o.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;o.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),o.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(o,r,e,n);for(let s of e.whereNodes)o.whereNodes.push(W(s));for(let s of e.orderByNodes)o.orderByNodes.push(W(s));return o}selectRelationColumnsWithAlias(e,r,n,o){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=n.selectNodes.filter(m=>typeof m.column=="string"),c=d.some(m=>m.column==="*"||m.column.endsWith(".*"));if(d.length===0||c)for(let[m,p]of u)e.selectRaw(`${a.table}.${m} as ${s}${o}${p.columnName}`);else for(let m of d){let p=m.column,h=p.includes(".")?p.split(".").pop():p,f=u.get(h)||l.get(h),T=f?.databaseName??h,w=m.alias??f?.columnName??h;e.selectRaw(`${a.table}.${T} as ${s}${o}${w}`);}}mapJoinedResultsToModels(e,r,n,o){let{columnName:s,type:a}=n,l=n.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];u.has(c)||u.set(c,[]);let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.get(c).push(m));}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||[];});}else {let u=new Map;e.forEach(d=>{let c=d[this.model.primaryKey];if(!u.has(c)){let m=this.extractRelationDataFromRow(d,s,o);m&&(this.serializeRelationData(m,l),u.set(c,m));}}),r.forEach(d=>{let c=d[this.model.primaryKey];d[s]=u.get(c)||null;});}}extractRelationDataFromRow(e,r,n){let o=`${r}${n}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(o)){let d=u.substring(o.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof M)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Re)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof $e)for(let n of e.nodes)this.qualifyWhereNodeColumns(n,r);}serializeRelationData(e,r){for(let n of Object.keys(e)){let o=r.get(n);o?.serialize&&e[n]!==null&&e[n]!==void 0&&(e[n]=o.serialize(e[n]));}}async loadRelationViaBatch(e,r){let n=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,n);}mapRelatedModelsToModels(e,r,n){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let o=new Map;n.forEach(m=>{let p=m[e.foreignKey];p&&o.set(String(p),m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=null;return}let h=o.get(String(p));m[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;n.forEach(m=>{if(!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=m[e.model.primaryKey];p&&s.set(String(p),m);}),r.forEach(m=>{let p=m[e.foreignKey];if(!p){m[e.columnName]=null;return}let h=s.get(String(p));m[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;n.forEach(m=>{let p=m[e.foreignKey];if(!p)return;let h=String(p);a.has(h)||a.set(h,[]),a.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=a.get(String(p))||[];m[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new S(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,c=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||H(d,this.model.modelCaseConvention);n.forEach(m=>{let p=m[c];if(p==null)return;let h=String(p);u.has(h)||u.set(h,[]),delete m[c],u.get(h).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let h=u.get(String(p))||[];m[e.columnName]=h;});break;default:throw new S(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,n){return this.getRelatedModelsQueryForRelation(e,r,n).many()}getRelatedModelsQueryForRelation(e,r,n){let o=this.getFilterValuesFromModelsForRelation(r,n);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,o);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,o);let l=Qe(Hl.crypto.randomBytes(6)),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(O=>O.isRawValue?O.column:`${this.interpreterUtils.formatStringColumn(this.dbType,O.column)} ${O.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let c=e.with(u,O=>O.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,o));s&&c.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&c.whereRaw(`rn_${l} > ${a}`);let m=e.modelSelectedColumns.map(O=>fo(O,u,e.model.table));return c.select(...m).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!n.length)return e;let h=e.limitNode?.limit,f=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(O=>O.includes(".")?O:`${r.model.table}.${O}`):[`${r.model.table}.*`];if(!h&&!f)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o);let w=Qe(Hl.crypto.randomBytes(6)),q=`${r.model.table}_cte_${w}`,D=e.orderByNodes.map(O=>{if(O.isRawValue)return O.column;let K=O.column.includes(".")?O.column:`${r.model.table}.${O.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,K)} ${O.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let R=`${Qe(Hl.crypto.randomBytes(6))}_left_foreign_key`,$=e.with(q,O=>O.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,R]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${D}) as rn_${w}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,o));h&&$.whereRaw(`rn_${w} <= ${h+(f||0)}`),f&&$.whereRaw(`rn_${w} > ${f}`);let A=T.map(O=>fo(O,q,e.model.table));return $.select(...A).select([`${q}.${R}`,p.leftForeignKey]).table(q);default:throw new S(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);case "belongsTo":return r.map(n=>n[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(n=>n[this.model.primaryKey]);default:throw new S(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,n,o){let s=new y(r.model),a=new y(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new S(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new S(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),n&&typeof o=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${n} ${o}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new S(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===u.throughModel&&p.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let c=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${c} = ${m}`),n&&typeof o=="number"&&e.groupByRaw(c).andHavingRaw(`count(*) ${n} ${o}`);return}default:throw new S(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}};function Zf(){return {}}var st=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=Zf(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new y(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,n])=>{e.orderBy(r,n);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many()}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,offset:t.offset});if(e===null)throw t.customError?t.customError:new S(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new S(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one()}insert(t,e={}){let r=this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(t).map(u=>[u,t[u]]))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),[r],e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new G(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(q){throw q}let{columns:u,values:d}=this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert",this.sqlType),c={};u.forEach((q,D)=>{let R=d[D];c[q]=R,t[q]??(t[q]=R);});let m=!e.returning||e.returning.length===0,{sql:p,bindings:h}=this.astParser.parse([new re(new U(this.model.table),[c],e.returning,m)]),f=await J(p,h,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(m)return;if(this.sqlType==="mysql")return this.handleMysqlInsert(f,[t],"one",e.returning);let T=f[0];return T?he([T],this.model,e.returning):t})}insertMany(t,e={}){let r=t.map(u=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(u).map(d=>[d,u[d]])))),n=!e.returning||e.returning.length===0,o=new re(new U(this.model.table),r,e.returning,n),s=()=>{let u=this.astParser.parse([o]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([o]);return {sql:lt(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return it(u,d)};return new G(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}let u=t.map(T=>{let{columns:w,values:q}=this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert",this.sqlType),D={};return w.forEach((R,$)=>{let A=q[$];D[R]=A,T[R]??(T[R]=A);}),D}),d=!e.returning||e.returning.length===0,{sql:c,bindings:m}=this.astParser.parse([new re(new U(this.model.table),u,e.returning,d)]),p=await J(c,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let h=p;return h.length?he(h,this.model,e.returning)||[]:[]})}upsertMany(t,e,r,n={updateOnConflict:true}){let o=this.interpreterUtils.filterComputedColumns(e),s=r.map(p=>this.interpreterUtils.stripComputedFromData(Object.fromEntries(Object.keys(p).map(h=>[h,p[h]])))),a=new re(new U(this.model.table),s,void 0,true),l=n.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0;new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",l);let d=()=>{let p=this.astParser.parse([a]);return {sql:p.sql,bindings:p.bindings}},c=()=>{let p=this.astParser.parse([a]);return {sql:lt(this.sqlDataSource,p.sql),bindings:p.bindings}},m=()=>{let{sql:p,bindings:h}=c();return it(p,h)};return new G(d,c,m,async()=>{let p=r.map(A=>{let{columns:O,values:K}=this.interpreterUtils.prepareColumns(Object.keys(A),Object.values(A),"insert",this.sqlType);return Object.fromEntries(O.map((le,v)=>[le,K[v]]))});if(this.sqlType==="mssql")return this.executeMssqlMerge(p,t,o,n,r);let h=!n.returning||n.returning.length===0,f=!h&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?n.returning:void 0,{sql:T,bindings:w}=this.astParser.parse([new re(new U(this.model.table),p,void 0,true),new Ce(this.model.table,t,o,n.updateOnConflict??true?"update":"ignore",f)]),q=await J(T,w,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(h)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(q.length<r.length&&!(n.updateOnConflict??true)){let K=t[0],le=r.map(ne=>ne[K]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(K,le).many()}return he(q,this.model,n.returning)||[]}let D=t[0],R=r.map(A=>A[D]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(D,R).many()})}async executeMssqlMerge(t,e,r,n,o){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=A=>this.interpreterUtils.formatStringColumn("mssql",A),u=[],d=t.map(A=>`select ${s.map(K=>(u.push(A[K]),`@${u.length}`)).join(", ")}`),c=s.map(l).join(", "),m=d.join(" union all "),p=e.map(A=>`target.${l(A)} = source.${l(A)}`).join(" and "),h=r.filter(A=>!e.includes(A)).map(A=>`target.${l(A)} = source.${l(A)}`).join(", "),f=s.map(l).join(", "),T=s.map(A=>`source.${l(A)}`).join(", "),w=n.returning&&n.returning.length?n.returning.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "):s.map(A=>`inserted.${l(A)}${this.interpreterUtils.resolveColumnAlias("mssql",A)}`).join(", "),D=(n.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",R=`merge into ${a} as target using (${m}) as source (${c}) on ${p} ${D} when not matched then insert (${f}) values (${T}) output ${w};`,$=await J(R,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});if($.length===0&&!(n.updateOnConflict??true)){let A=e[0],O=o.map(le=>le[A]);return await this.query().select(...n.returning?.length?n.returning:["*"]).whereIn(A,O).many()}return $}async updateRecord(t,e,r){let n=new Set(this.model.getColumns().map(w=>w.columnName)),o=Object.keys(e).filter(w=>n.has(w)),s=o.map(w=>e[w]),{columns:a,values:l}=this.interpreterUtils.prepareColumns(o,s,"update",this.sqlType),{primaryKey:u}=this.model;if(!u)throw new S(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let c=r?.returning??[],m=c.length>0&&!this.interpreterUtils.hasComputedColumn(c)&&this.interpreterUtils.shouldFetchNatively(this.sqlType,"update"),{sql:p,bindings:h}=this.astParser.parse([new Ee(new U(this.model.table),a,l),new M(u,"and",false,"=",t),...m?[new xt(c)]:[]]),f=await J(p,h,this.sqlDataSource,this.sqlType,m?"rows":"affectedRows",m?{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}:void 0);if(!c.length)return;if(m){if(!f.length)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return he([f[0]],this.model,c)}let T=await this.findOneByPrimaryKey(t,r?.returning);if(!T)throw new S(this.model.name+"::updateRecord","ROW_NOT_FOUND");return T}async deleteRecord(t){if(!this.model.primaryKey)throw new S(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new M(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:n}=this.astParser.parse([new Mt(new U(this.model.table)),e]);await J(r,n,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new ot(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,n){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?he([a],this.model):null}return he(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...n??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let o=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...n||["*"]).whereIn(this.model.primaryKey,o).many();return r==="one"?s.length?s[0]:null:s}handleWhereCondition(t,e,r=false){if(e)for(let[n,o]of Object.entries(e))n==="$and"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{for(let l of o)this.handleWhereCondition(a,l,false);}):n==="$or"&&Array.isArray(o)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of o)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,n,o,r);}applyFieldCondition(t,e,r,n=false){if(r==null||typeof r!="object"){r===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",r):t.where(e,"=",r);return}let o=r,s=o.op,a=o.value;switch(s){case "$eq":a===null?n?t.orWhereNull(e):t.whereNull(e):n?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?n?t.orWhereNotNull(e):t.whereNotNull(e):n?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":n?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":n?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":n?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":n?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;n?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;n?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":n?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":n?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":n?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":n?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":n?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":n?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":n?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":n?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":n?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":n?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:n?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var zl=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??bt()});Dt();var be=class{constructor(t){this.options=t;}static async createDriver(t){throw new S("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};ue();var Ht=class Ht extends be{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new Ht(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new L("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new L("mongodb");return new Ht(this.mongoClient)}};Ht.mongoClient=null;var gn=Ht;ue();var zt=class zt extends be{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new zt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new L("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new L("mssql");return new zt(this.mssqlClient)}};zt.mssqlClient=null;var bn=zt;ue();var Gt=class Gt extends be{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Gt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new L("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new L("mysql2");return new Gt(this.mysqlClient)}};Gt.mysqlClient=null;var Tn=Gt;ue();var Yt=class Yt extends be{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Yt(this.pgClient);let e=await import('pg').catch(()=>{throw new L("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new L("pg");return new Yt(this.pgClient)}};Yt.pgClient=null;var wn=Yt;ue();var Zt=class Zt extends be{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new Zt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new L("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new L("sqlite3");return new Zt(this.sqlite3Client)}};Zt.sqlite3Client=null;var Sn=Zt;var me=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Tn.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await wn.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Sn.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await gn.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await bn.createDriver(),this.mssqlDriver;default:throw new S(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;default:return null}}};me.mysqlDriver=null,me.pgDriver=null,me.sqliteDriver=null,me.mssqlDriver=null,me.mongodbDriver=null;Dt();ue();var Nn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.coerceNumericTypes&&!e.driverOptions?.types?{getTypeParser:(o,s)=>{let a=!s||s==="text";return a&&o===20?l=>BigInt(l):a&&o===1700?l=>Number.parseFloat(l):r.types.getTypeParser(o,s)}}:void 0;this.pool=new r.Pool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions,...n?{types:n}:{}});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.connect()}releaseConnection(t){t?.release();}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION"),e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`);}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){let n=0,o=t.replace(/\?/g,()=>`$${++n}`);if(!r.signal)return (r.connection??this.pool).query(o,e);let s=r.connection??await this.pool.connect(),a=!r.connection,l=()=>{let u=s.processID;u!=null&&this.pool.query("SELECT pg_cancel_backend($1)",[u]).catch(()=>{});};r.signal.addEventListener("abort",l,{once:true});try{return await s.query(o,e)}finally{r.signal.removeEventListener("abort",l),a&&s.release();}}extract(t,e){return e==="rows"?t.rows:e==="raw"?t:t.rowCount}async stream(t,e,r,n){let o=r.connection,s=!o,a=o??await this.pool.connect(),l=await import('pg-query-stream').catch(()=>{throw new L("pg-query-stream")}),u=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=0,c=t.replace(/\?/g,()=>`$${++d}`),m=new l.default(c,e,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(m),h=0,f=false,T=false,w=q=>{if(s)try{a.release(q);}catch{}};return p.on("data",q=>{if(n.onData){h++,Promise.resolve(n.onData(u,q)).then(()=>{h--,f&&h===0&&!T&&(w(),u.end());}).catch(D=>{T=true,w(D),u.destroy(D);});return}u.write(q);}),p.on("end",()=>{f=true,h===0&&!T&&(w(),u.end());}),p.on("error",q=>{T=true,w(q),u.destroy(q);}),u}};var qn=class{constructor(t,e,r){this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=r.createPool({host:e.host,port:e.port,user:e.username,password:e.password,database:e.database,...e.driverOptions});}createPool(){}async closePool(){await this.pool.end();}async reserveConnection(){return this.pool.getConnection()}releaseConnection(t){t?.release();}async beginTransaction(t,e){e.isolationLevel&&await e.rawQuery(`SET TRANSACTION ISOLATION LEVEL ${e.isolationLevel}`),await t.beginTransaction();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){if(!r.signal)return (r.connection??this.pool).query(t,e);let n=r.connection??await this.pool.getConnection(),o=!r.connection,s=()=>{let a=n.threadId;a!=null&&this.pool.query(`KILL QUERY ${Number(a)}`).catch(()=>{});};r.signal.addEventListener("abort",s,{once:true});try{return await n.query(t,e)}finally{r.signal.removeEventListener("abort",s),o&&n.release();}}extract(t,e){let r=t;return e==="affectedRows"?r[0]?.affectedRows??0:e==="raw"?t:r[0]}async stream(t,e,r,n){let o=this.pool,s=r.connection??await o.getConnection(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=s.connection.query(t,e).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),d=0,c=false,m=false,p=()=>{try{s.release();}catch{}};return u.on("data",h=>{if(n.onData){d++,Promise.resolve(n.onData(a,h)).then(()=>{d--,c&&d===0&&!m&&(p(),a.end());}).catch(f=>{m=true,p(),a.destroy(f);});return}a.write(h);}),u.on("end",()=>{c=true,d===0&&!m&&(p(),a.end());}),u.on("error",h=>{m=true,p(),a.destroy(h);}),a.on("close",()=>{p();}),a}};var Cn=class{constructor(t,e,r){this.dialect="sqlite";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e,this.pool=new r.Database(String(e.database??":memory:"),e.driverOptions?.mode??void 0,n=>{if(n)throw new S("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});}createPool(){}async closePool(){await new Promise((t,e)=>{this.pool.close(r=>{r&&e(r),t();});});}async reserveConnection(){return this.pool}releaseConnection(){}async beginTransaction(t,e){await e.rawQuery("BEGIN TRANSACTION");}async commitTransaction(t,e){await e.rawQuery("COMMIT");}async rollbackTransaction(t,e){await e.rawQuery("ROLLBACK");}async execute(t,e,r){return await this.promisify(t,e,r)}extract(t,e){return e==="raw"?Array.isArray(t)?t:[t]:t}async stream(t,e,r,n){let o=r.connection??this.pool;return new Gl(o,t,e,{onData:n.onData})}promisify(t,e,r){let n=r.sqlLiteOptions??{},o=n.mode||"fetch",s=n.customConnection??r.connection??this.pool;if(["begin","begin transaction","commit","rollback"].includes(t.trim().toLowerCase()))return new Promise((u,d)=>{s.run(t,e,function(c){c&&d(c),u(this.changes);});});if(o==="fetch")return new Promise((u,d)=>{s.all(t,e,(c,m)=>{c&&d(c),u(m||[]);});});if(!n?.typeofModel)return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});});if(o==="insertOne"||o==="insertMany"){let u=`${t} returning *`;return new Promise((d,c)=>{s.all(u,e,(m,p)=>{if(m)return c(m);d(p||[]);});})}return new Promise((u,d)=>{s.run(t,e,function(c){c?d(new Error(c.message)):u(this.changes);});})}},Gl=class extends Readable{constructor(t,e,r=[],n){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=n;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(n,o)=>{if(n){r=true,this.emit("error",n);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,o)).then(()=>{if(!r){if(s){this.push(a);return}this.push(o);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},n=>{if(n){r=true,this.emit("error",n);return}e=true,t===0&&!r&&this.push(null);});}};ue();var Rn=class{constructor(t,e,r){this.dialect="mssql";this.jsEnvironment="node";this.dialect=t,this.client=r,this.input=e;let n=e.driverOptions,{options:o,...s}=n??{};this.pool=new r.ConnectionPool({server:e.host??"localhost",port:e.port,database:e.database,user:e.username,password:e.password,...s,options:{trustServerCertificate:E.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...o,abortTransactionOnError:false,enableImplicitTransactions:false}});}async createPool(){await this.pool.connect();}async closePool(){await this.pool.close();}async reserveConnection(){return this.pool.transaction()}releaseConnection(){}async beginTransaction(t,e){if(e.isolationLevel){let r=await this.getMssqlTransactionLevel(e.isolationLevel);await t.begin(r);return}await t.begin();}async commitTransaction(t,e){await t.commit();}async rollbackTransaction(t,e){await t.rollback();}async execute(t,e,r){let n=this.pool,o=r.connection?r.connection.request():n.request();e.forEach((l,u)=>{o.input(`p${u}`,l);});let s=0,a=t.replace(/\?|@(\d+)/g,()=>`@p${s++}`);if(r.signal){let l=()=>{try{o.cancel();}catch{}};r.signal.addEventListener("abort",l,{once:true});try{return await o.query(a)}finally{r.signal.removeEventListener("abort",l);}}return o.query(a)}extract(t,e){return e==="affectedRows"?t.rowsAffected[0]:e==="raw"?t:t.recordset}async stream(t,e,r,n){let o=r.connection??this.pool,s=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),a=o.request();a.stream=true,e.forEach((p,h)=>{a.input(`p${h}`,p);});let l=0,u=t.replace(/\?|@(\d+)/g,()=>`@p${l++}`),d=0,c=false,m=false;return a.on("row",p=>{if(!m){if(n.onData){d++,Promise.resolve(n.onData(s,p)).then(()=>{d--,c&&d===0&&!m&&s.end();}).catch(h=>{m=true,s.destroy(h);});return}s.write(p);}}),a.on("error",p=>{m=true,s.destroy(p);}),a.on("done",()=>{c=true,d===0&&!m&&s.end();}),a.query(u),s}async getMssqlTransactionLevel(t){let e=await import('mssql').then(r=>r.default.ISOLATION_LEVEL).catch(r=>{throw g.error(r),new L("mssql")});switch(t){case "READ UNCOMMITTED":return e.READ_UNCOMMITTED;case "READ COMMITTED":return e.READ_COMMITTED;case "REPEATABLE READ":return e.REPEATABLE_READ;case "SERIALIZABLE":return e.SERIALIZABLE;default:throw new S("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${t}`)}}};var yg=()=>{ge({name:"pg",dialects:["postgres","cockroachdb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Nn(i,t,e)}}),ge({name:"mysql2",dialects:["mysql","mariadb"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new qn(i,t,e)}}),ge({name:"sqlite3",dialects:["sqlite"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Cn(i,t,e)}}),ge({name:"mssql",dialects:["mssql"],create:async({dialect:i,input:t})=>{let e=(await me.getDriver(i)).client;return new Rn(i,t,e)}});};yg();var Sg=async i=>{if(i==="bun"){await(await Promise.resolve().then(()=>(ay(),iy))).registerBunDrivers();return}if(i==="web"){(await Promise.resolve().then(()=>(tu(),eu))).registerWebDrivers();return}if(i==="react-native"){await(await Promise.resolve().then(()=>(tu(),eu))).registerReactNativeDrivers();return}},Dn=async(i,t)=>{let e=ur(t?.jsEnvironment);await Sg(e);let r=await ey(i,e,t?.driver,t);return await r.createPool(),r};var er=class er{constructor(){}static run(t,e){return er.storage.run(t,e)}static getTransaction(){return er.storage.getStore()}};er.storage=new AsyncLocalStorage;var He=er;var tr=class i{constructor(t,e,r=false,n=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Qe(ie().crypto.randomBytes(16)),this.isolationLevel=e,this.isNested=r,this.nestingDepth=n;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await He.run(e,()=>t(e));return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){if(this.getIsolationLevelQuery(),this.isNested){let r=this.getSavePointName();this.sql.type==="mssql"?await this.sql.rawQuery(`SAVE TRANSACTION ${r}`):await this.sql.rawQuery(`SAVEPOINT ${r}`),this.isActive=true;return}(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("BEGIN TRANSACTION",this.sql.logs);let t=this.sql.driverAdapter,e=this.sql.sqlConnection;if(!t||!e)throw new S("TRANSACTION::transaction","CONNECTION_NOT_ESTABLISHED");await t.beginTransaction(e,{isolationLevel:this.isolationLevel,rawQuery:(r,n)=>this.sql.rawQuery(r,n??[])}),this.isActive=true;}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("COMMIT",this.sql.logs),e&&r&&await e.commitTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new S("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new S("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=false;return}try{let e=this.sql.driverAdapter,r=this.sql.sqlConnection;(this.sql.type==="mssql"||this.sql.type==="mysql"||this.sql.type==="mariadb")&&ct("ROLLBACK",this.sql.logs),e&&r&&await e.rollbackTransaction(r,{rawQuery:(n,o)=>this.sql.rawQuery(n,o??[])});}catch(e){throw g.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async releaseConnection(){if(this.connectionReleased)return;let t=null;try{this.sql.driverAdapter?.releaseConnection(this.sql.sqlConnection);}catch(e){t=e,g.error(e);}this.sql.sqlConnection=null;try{await this.sql.disconnect();}catch(e){g.warn(`Transaction::releaseConnection - disconnect failed: ${e?.message??e}`);}if(this.connectionReleased=true,t)throw t}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new S("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new S("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}};var ru=Symbol.for("hysteria.orm.SqlDataSource"),my,py,Be=class i extends(py=kt,my=ru,py){constructor(e){super(e);this[my]=true;this.globalTransaction=null;this.globalTransactionLock=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.lockConnection=null;this.lockKeyToId=new Map;this.driverAdapter=null;this.id=ie().crypto.randomUUID();this.logicalSourceId=ie().crypto.randomUUID();this.cacheAdapter=new hr;this.migrationConfig={path:E.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.zodEngine=null;this.lazyLoad=false;this.connecting=null;this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:vt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(n=>new i(n)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure,this.lazyLoad=e?.lazyLoad??false,this.clsEnabled=e?.clsEnabled??true;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&ru in e&&e[ru]===true}get isClsEnabled(){return this.clsEnabled}getOnSlaveServerFailure(){return this.onSlaveServerFailure}addObserver(e){return this.observerChain||(this.observerChain=new Ft([])),this.observerChain.add(e),this}static async useConnection(e,r){let n=new i(e);await n.connect();try{await r(n),n.isConnected&&await n.disconnect();}catch(o){throw n.isConnected&&await n.disconnect(),o}}async connect(){if(this.isConnected)throw new S("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");try{this.driverAdapter=await Dn(this.sqlType,this.inputDetails),this.sqlPool=this.driverAdapter.pool??null,this.ownsPool=!0,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.driverAdapter=await Dn(e.sqlType,e.inputDetails),e.sqlPool=e.driverAdapter.pool??null,e.ownsPool=!0;}));}catch(e){this.sqlPool=null,this.ownsPool=false;for(let r of this.slaves)r.ownsPool&&(r.sqlPool=null,r.ownsPool=false);throw e}}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new S("SqlDataSource::ensureConnected","CONNECTION_NOT_ESTABLISHED");this.connecting||(this.connecting=this.connect().finally(()=>{this.connecting=null;})),await this.connecting;}}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){let e=this;return new Proxy(this._models,{get(r,n){if(typeof n=="string"&&n in r)return e.from(r[n])}})}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}getTransactionBoundSqlDataSource(){if(this.globalTransaction?.isActive)return this.globalTransaction.sql;if(this.clsEnabled){let e=He.getTransaction();if(e?.isActive&&e.sql.logicalSourceId===this.logicalSourceId)return e.sql}return null}async useCache(e,r,...n){if(!this.cacheAdapter)throw new S("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new S("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=o.length,a=typeof r=="number"&&s===n.length,l,u=[];a?(l=r,u=n):(l=void 0,u=r!==void 0?[r,...n]:n);let d=Hn(JSON.stringify(u)),c=d?`${e}:${d}`:e,m=await this.cacheAdapter.get(c);if(m!==void 0)return m;let p=await o(...u);return await this.cacheAdapter.set(c,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new S("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(n.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Hn(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new S("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.id=this.id,r.logicalSourceId=this.logicalSourceId,r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.driverAdapter=await Dn(r.sqlType,this.inputDetails),r.sqlPool=r.driverAdapter.pool,r.ownsPool=true):(r.driverAdapter=this.driverAdapter,r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let n=this.getTransactionBoundSqlDataSource()??this;if(typeof e=="string"){let o=new B(zl(e,r),n);return r?.alias&&o.table(e,r.alias),o}return new ot(e,n)}fromRaw(e,r=[],n){let o=this.getTransactionBoundSqlDataSource()??this;return new B(zl("",n),o).fromRaw(e,r)}schema(){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Wt(this,this.getDbType())}async startGlobalTransaction(e){for(;this.globalTransactionLock;)await this.globalTransactionLock;if(this.globalTransaction?.isActive)throw new S("SqlDataSource::startGlobalTransaction","GLOBAL_TRANSACTION_ALREADY_STARTED");let r=()=>{};this.globalTransactionLock=new Promise(n=>{r=n;});try{let n=await this.clone();return n.sqlConnection=await n.getConnection(),this.globalTransaction=new tr(n,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}finally{r(),this.globalTransactionLock=null;}}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new S("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");try{await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}try{await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async transaction(e,r){let n=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let o=this.clsEnabled?He.getTransaction():void 0;if(o?.isActive&&o.sql.logicalSourceId===this.logicalSourceId)return typeof e=="function"?o.nestedTransaction(e):o.nestedTransaction();let s=await this.clone();s.sqlConnection=await s.getConnection();let a=new tr(s,n?.isolationLevel);if(await a.transaction(),typeof e=="function")try{let l=this.clsEnabled?await He.run(a,()=>e(a)):await e(a);return await a.commit({throwErrorOnInactiveTransaction:!1}),l}catch(l){throw await a.rollback({throwErrorOnInactiveTransaction:false}),l}return a}getModelManager(e){if(!this.isConnected&&!this.lazyLoad)throw new S("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");let r=this.getTransactionBoundSqlDataSource()??this;return new st(e,r)}getPool(){if(!this.sqlPool)throw this.lazyLoad?new S("SqlDataSource::getPool - call ensureConnected() or connect() first when using lazyLoad","CONNECTION_NOT_ESTABLISHED"):new S("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;await this.ensureConnected();let e=this.driverAdapter;if(!e)throw new S("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");return e.reserveConnection()}async disconnect(){if(!this.isConnected){g.warn("Connection already closed or not established");return}if(!this.ownsPool){if(this.sqlConnection)try{this.driverAdapter?.releaseConnection(this.sqlConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing borrowed connection failed: ${e?.message??e}`);}this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}if(this.lockConnection){try{this.driverAdapter?.releaseConnection(this.lockConnection);}catch(e){g.warn(`SqlDataSource::disconnect - releasing lock connection failed: ${e?.message??e}`);}this.lockConnection=null,this.lockKeyToId.clear();}await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),g.warn("Closing connection"),await this.driverAdapter?.closePool(),this.sqlPool=null,this.driverAdapter=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions,jsEnvironment:this.inputDetails.jsEnvironment,driver:this.inputDetails.driver}}async introspectSchema(){let e=this.getDbType(),r;e==="postgres"||e==="cockroachdb"?r=`
|
|
260
260
|
SELECT table_schema AS schema_name, table_name
|
|
261
261
|
FROM information_schema.tables
|
|
262
262
|
WHERE table_type = 'BASE TABLE'
|