hysteria-orm 10.7.1 → 10.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cli.js +1 -1
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +2 -2
- package/lib/index.d.ts +2 -2
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -286,7 +286,7 @@ ORDER BY ordinal_position`,bindings:[]}}},sc=new vi;var ki=class{toSql(t){let e=
|
|
|
286
286
|
FROM pragma_table_info('${t.table}')
|
|
287
287
|
WHERE pk > 0
|
|
288
288
|
ORDER BY pk`,bindings:[]}}},ep=new $a;var Oa=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},tp=new Oa;var Ia=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new f(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new b(this.model,"sqlite").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new b(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new f(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new b(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",d=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(d))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),d=0;for(let u of l)u==="("&&d++,u===")"&&d--;if(d>0)return e}return `as "${r}"`})}},rp=new Ia;var Da=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new f(this.model).formatStringColumn("sqlite",e.column),o=se.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},op=new Da;var Ea=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new f(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},np=new Ea;var va=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),o=Array.isArray(e.query)?e.query:[e.query],n=typeof e.query=="string"?{sql:e.query,bindings:[]}:r.parse(o.filter(Boolean),e.currParamIndex);return {sql:n.sql,bindings:n.bindings}}},sp=new va;var ka=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new f(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let d=e.values[l];return d instanceof $?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},ip=new ka;var Qa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new f(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new f(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new f(this.model).formatStringColumn("sqlite",t):t}},ap=new Qa;var Ba=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new b(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},lp=new Ba;var Ka=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new f(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},dp=new Ka;var La=class{toSql(t){let e=t;return this.isStringSubquery(e.subquery)?this.handleStringSubquery(e):this.isArraySubquery(e.subquery)?this.handleArraySubquery(e):this.handleObjectSubquery(e)}isStringSubquery(t){return typeof t=="string"}isArraySubquery(t){return Array.isArray(t)}handleStringSubquery(t){return {sql:`${t.column} ${t.operator} (${t.subquery})`.trim(),bindings:[]}}handleArraySubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:o}=e.parse(t.subquery,t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}handleObjectSubquery(t){let e=new b(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},up=new La;var Wa=class{toSql(t){let e=t,r=new b(this.model,"sqlite"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex);return {sql:`${e.alias} as (${n.sql})`,bindings:n.bindings}}},mp=new Wa;var cp={mssql:{alter_table:{add_column:dl,add_constraint:ul,add_primary_key:ml,alter_column_type:cl,alter_table:Ol,drop_column:Il,drop_constraint:Dl,drop_default:El,drop_not_null:vl,drop_primary_key:kl,rename_column:Ql,rename_table:Bl,set_default:Kl,set_not_null:Ll,set_table_options:Wl},column:{column_type:Ul},constraint:{after:Fl,constraint:jl},create_table:{create_table:Vl},delete:{delete:Jl},distinct:{distinct:Hl,distinct_on:Yl},drop_table:{drop_table:Gl},extension:{create_extension:zl},from:{from:Zl},group_by:{group_by:Xl},having:{having:ed},index_op:{create_index:td,drop_index:rd},insert:{insert:od},join:{join:nd},limit:{limit:sd},lock:{lock:id},offset:{offset:ad},on_duplicate:{on_duplicate:ld},order_by:{order_by:dd},raw:{raw:ud},schema:{foreign_key_info:md,index_info:cd,primary_key_info:pd,table_info:fd},select:{select:yd,select_json:hd},truncate:{truncate:gd},union:{union:bd},update:{update:Td},where:{where:Nd,where_group:wd,where_json:Sd,where_subquery:qd},with:{with:Md}},mysql:{alter_table:{add_column:_d,add_constraint:Cd,add_primary_key:Rd,alter_column_type:xd,alter_table:Ad,drop_column:Pd,drop_constraint:$d,drop_default:Od,drop_not_null:Id,drop_primary_key:Dd,rename_column:Ed,rename_table:vd,set_default:kd,set_not_null:Qd,set_table_options:Bd},column:{column_type:Kd},constraint:{after:Ld,constraint:Wd},create_table:{create_table:Ud},delete:{delete:Fd},distinct:{distinct:jd,distinct_on:Vd},drop_table:{drop_table:Jd},extension:{create_extension:Hd},from:{from:Yd},group_by:{group_by:Gd},having:{having:zd},index_op:{create_index:Zd,drop_index:Xd},insert:{insert:eu},join:{join:tu},limit:{limit:ru},lock:{lock:ou},offset:{offset:nu},on_duplicate:{on_duplicate:su},order_by:{order_by:iu},raw:{raw:au},schema:{foreign_key_info:lu,index_info:du,primary_key_info:uu,table_info:mu},select:{select:cu,select_json:pu},truncate:{truncate:fu},union:{union:yu},update:{update:hu},where:{where:gu,where_group:bu,where_json:Tu,where_subquery:Nu},with:{with:wu}},oracledb:{alter_table:{add_column:Su,add_constraint:qu,add_primary_key:Mu,alter_column_type:_u,alter_table:Cu,drop_column:Ru,drop_constraint:xu,drop_default:Au,drop_not_null:Pu,drop_primary_key:$u,rename_column:Ou,rename_table:Iu,set_default:Du,set_not_null:Eu,set_table_options:vu},column:{column_type:ku},constraint:{after:Qu,constraint:Bu},create_table:{create_table:Ku},delete:{delete:Lu},distinct:{distinct:Wu,distinct_on:Uu},drop_table:{drop_table:Fu},extension:{create_extension:ju},from:{from:Vu},group_by:{group_by:Ju},having:{having:Hu},index_op:{create_index:Yu,drop_index:Gu},insert:{insert:zu},join:{join:Zu},limit:{limit:Xu},lock:{lock:em},offset:{offset:tm},on_duplicate:{on_duplicate:rm},order_by:{order_by:om},raw:{raw:nm},schema:{foreign_key_info:sm,index_info:im,primary_key_info:am,table_info:lm},select:{select:dm,select_json:um},truncate:{truncate:mm},union:{union:cm},update:{update:pm},where:{where:fm,where_group:ym,where_json:hm,where_subquery:gm},with:{with:bm}},postgres:{alter_table:{add_column:Tm,add_constraint:Nm,add_primary_key:wm,alter_column_type:Sm,alter_table:qm,drop_column:Mm,drop_constraint:_m,drop_default:Cm,drop_not_null:Rm,drop_primary_key:xm,rename_column:Am,rename_table:Pm,set_default:$m,set_not_null:Om,set_table_options:Im},column:{column_type:Dm},constraint:{after:Em,constraint:vm},create_table:{create_table:km},delete:{delete:Qm},distinct:{distinct:Bm,distinct_on:Km},drop_table:{drop_table:Lm},extension:{create_extension:Wm},from:{from:Um},group_by:{group_by:Fm},having:{having:jm},index_op:{create_index:Vm,drop_index:Jm},insert:{insert:Hm},join:{join:Ym},limit:{limit:Gm},lock:{lock:zm},offset:{offset:Zm},on_duplicate:{on_duplicate:Xm},order_by:{order_by:ec},raw:{raw:tc},schema:{foreign_key_info:rc,index_info:oc,primary_key_info:nc,table_info:sc},select:{select:ic,select_json:ac},truncate:{truncate:lc},union:{union:dc},update:{update:uc},where:{where:mc,where_group:cc,where_json:pc,where_subquery:fc},with:{with:yc}},sqlite:{alter_table:{add_column:hc,add_constraint:gc,alter_column_type:bc,alter_table:Tc,drop_column:Nc,drop_constraint:wc,drop_default:Sc,drop_not_null:qc,drop_primary_key:Mc,rename_column:_c,rename_table:Cc,set_default:Rc,set_not_null:xc,set_table_options:Ac},column:{column_type:Pc},constraint:{after:$c,constraint:Oc},create_table:{create_table:Ic},delete:{delete:Dc},distinct:{distinct:Ec,distinct_on:vc},drop_table:{drop_table:kc},extension:{create_extension:Qc},from:{from:Bc},group_by:{group_by:Kc},having:{having:Lc},index_op:{create_index:Wc,drop_index:Uc},insert:{insert:Fc},join:{join:jc},limit:{limit:Vc},lock:{lock:Jc},offset:{offset:Hc},on_duplicate:{on_duplicate:Yc},order_by:{order_by:Gc},raw:{raw:zc},schema:{foreign_key_info:Zc,index_info:Xc,primary_key_info:ep,table_info:tp},select:{select:rp,select_json:op},truncate:{truncate:np},union:{union:sp},update:{update:ip},where:{where:ap,where_group:lp,where_json:dp,where_subquery:up},with:{with:mp}}};var b=class{constructor(t,e){this.dbType=e,this.model=t;}parse(t,e=1,r=false){if(!t.length)return {sql:"",bindings:[]};let o=t.find(_=>!!_&&_.folder==="distinctOn"),n=!o&&t.find(_=>!!_&&_.folder==="distinct"),s=this.dbType==="mssql"?t.find(_=>!!_&&_.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(_=>_!==null&&_.folder!=="distinct"&&_.folder!=="distinctOn"),d=l.some(_=>_.folder==="offset"),u=l.some(_=>_.folder==="order_by"),c=l.find(_=>_.folder==="limit"),m=l.find(_=>_.folder==="offset"),p=this.dbType==="mssql"&&c&&!d&&!u,y=this.dbType==="mssql"&&!p&&(c||m),h=this.dbType==="oracledb"&&(c||m),T=[],S=[],M=null;p&&c&&S.push(c.limit);for(let _=0;_<l.length;_++){let P=l[_];if(p&&P.folder==="limit"||y&&(P.folder==="limit"||P.folder==="offset")||h&&(P.folder==="limit"||P.folder==="offset"))continue;P.currParamIndex=e+S.length;let O=cp[this.mapCommonDbType(this.dbType)][P.folder][P.file];if(!O)throw new Error(`Interpreter not found for ${this.dbType} ${P.keyword}`);O.model=this.model;let R=O.toSql(P);if(!R.sql||!R.sql.trim().length)continue;let Q=l[_+1],D=!Q||Q.keyword!==P.keyword?"":Q.chainsWith;if(P.folder==="lock"||P.folder==="on_duplicate"||P.folder==="schema"){T.push(`${R.sql}${D}`),S.push(...R.bindings),M=P.keyword;continue}if(M!==P.keyword||P.canKeywordBeSeenMultipleTimes){if(r)T.push(`${R.sql}${D}`);else {let Y=P.keyword;if(P.folder==="with"&&this.dbType!=="mssql"){let Z=_,Te=false;for(;Z<l.length&&l[Z].keyword===P.keyword;){let _e=l[Z];if(_e.folder==="with"&&_e.clause==="recursive"){Te=true;break}Z++;}Te&&(Y=`${Y} recursive`);}if(Y==="select"){let Z=p?`top (@${e}) `:"";if(o){let Te=Array.isArray(o.columns)?o.columns.join(", "):"";T.push(`select ${Z}distinct on (${Te}) ${R.sql}${D}`);}else n?T.push(`select ${Z}distinct ${R.sql}${D}`):T.push(`select ${Z}${R.sql}${D}`);}else Y==="from"&&a?T.push(`${Y} ${R.sql}${a}${D}`):T.push(`${Y} ${R.sql}${D}`);}M=P.keyword;}else T.push(`${R.sql}${D}`);S.push(...R.bindings);}if(y){u||T.push("order by (select null)");let _=m?.offset??0;S.push(_);let O=`offset @${e+S.length-1} rows`;if(c){S.push(c.limit);let R=e+S.length-1;O+=` fetch next @${R} rows only`;}T.push(O);}if(h){u||T.push("order by null");let _=m?.offset??0;S.push(_);let O=`offset :${e+S.length-1} rows`;if(c){S.push(c.limit);let R=e+S.length-1;O+=` fetch next :${R} rows only`;}T.push(O);}return {sql:T.join(" "),bindings:S}}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 er=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var tr=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var rr=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var or=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var nr=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var de=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var ot=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var sr=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var ge=class extends w{constructor(e,r=[],o=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=o;}};var ir=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var be=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var St=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var ar=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var nt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var lr=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var dr=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var ur=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var Le=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var F=class extends w{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var mr=class extends w{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var cr=class extends w{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var pr=class extends w{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var fr=class extends w{constructor(e,r,o,n=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=o,this.unique=n;}};var yr=class extends w{constructor(e,r,o){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=o??false;}};var st=class extends w{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var v=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false;}};var qt=class extends w{constructor(e,r=false,o=false){super("lock");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="lock";this.file="lock";this.lockType=e,this.skipLocked=r,this.noWait=o;}};var We=class extends w{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var it=class extends w{constructor(e,r,o){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=o,this.clause=e;}};var Oe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var hr=class extends w{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var gr=class extends Oe{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=$e(this.tableName,q(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new F("primary_key",{columns:[q(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new F("primary_key",{columns:[q(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??G(this.tableName??"",q(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new F("foreign_key",{columns:[q(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new F("foreign_key",{columns:[q(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}notNullable(){return this.nodes.push(new F("not_null",{columns:[q(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new F("null",{columns:[q(this.columnNode.column)]})),this}default(t){let e;return t instanceof $?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new F("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new F("unique",{columns:[q(this.columnNode.column)],constraintName:t?.constraintName??le(this.tableName??"",q(this.columnNode.column))})),this):(this.namedConstraints.push(new F("unique",{columns:[q(this.columnNode.column)],constraintName:t?.constraintName||le(this.tableName??"",q(this.columnNode.column))})),this)}check(t,e){let r=q(this.columnNode.column),o=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new F("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new F("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new hr(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.nodes.push(new F("primary_key",{columns:[q(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Ue=class extends Oe{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new gr(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new $(e)}char(e,r=1){let o=new v(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new v(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new v(e,r);return this.build(o)}longtext(e){return this.text(e,"longtext")}mediumtext(e){return this.text(e,"mediumtext")}tinytext(e){return this.text(e,"tinytext")}uuid(e){let r=new v(e,"uuid");return this.build(r)}ulid(e){let r=new v(e,"ulid");return this.build(r)}integer(e,r=255){let o=new v(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new v(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new v(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new v(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new v(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new v(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new v(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new v(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new v(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new v(e,"numeric",{precision:r,scale:o});return this.build(n)}increment(e,r=255){return this.integer(e,r).increment()}bigIncrement(e,r=255){return this.biginteger(e,r).increment()}date(e,r){let o=new v(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new v(e,"time",{precision:r});return this.build(o)}year(e){let r=new v(e,"year");return this.build(r)}datetime(e,r){let o=new v(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}timestamp(e,r){let o=new v(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}boolean(e){let r=new v(e,"boolean");return this.build(r)}binary(e){let r=new v(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new v(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new v(e,"blob");return this.build(r)}tinyblob(e){let r=new v(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new v(e,"mediumblob");return this.build(r)}longblob(e){let r=new v(e,"longblob");return this.build(r)}json(e){let r=new v(e,"json");return this.build(r)}jsonb(e){let r=new v(e,"jsonb");return this.build(r)}enum(e,r){let o=new v(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new v(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new v(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new v(e,"geometry");return this.build(r)}point(e){let r=new v(e,"point");return this.build(r)}linestring(e){let r=new v(e,"linestring");return this.build(r)}polygon(e){let r=new v(e,"polygon");return this.build(r)}multiPoint(e){let r=new v(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var br=class extends Oe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new $(t)}addColumn(t){let e=[],r=new Ue(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(c=>c.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(c=>{let m=c;return m.constraintType==="not_null"||m.constraintType==="null"||m.constraintType==="default"}),d=new nr(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(c=>{let m=c;return m.constraintType==="unique"||m.constraintType==="foreign_key"||m.constraintType==="primary_key"}).forEach(c=>{this.nodes.push(new de(c));});}alterColumn(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Ue(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(p=>p.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=q(s.column),l=o.getNodes().find(p=>p.constraintType==="null"),u=o.getNodes().find(p=>p.constraintType==="not_null")||l,c=o.getNodes().find(p=>p.constraintType==="default"),m={};u&&(m.nullable=u.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 sr(q(a),s,m)),u&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(u.constraintType==="not_null"?this.nodes.push(new ur(q(a))):u.constraintType==="null"&&this.nodes.push(new ar(q(a)))),c&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(c.defaultValue===void 0||c.defaultValue===null||c.defaultValue==="NULL"?this.nodes.push(new St(q(a))):this.nodes.push(new dr(q(a),c.defaultValue))),o.getNodes().forEach(p=>{let y=p;switch(y.constraintType){case "primary_key":this.addPrimaryKey(q(a));break;case "unique":this.unique(q(a),{constraintName:y.constraintName});break;case "foreign_key":this.foreignKey(q(a),y.references?.table??"",q(y.references?.columns?.[0]??""),{constraintName:y.constraintName,onDelete:y.onDelete,onUpdate:y.onUpdate});break}});}dropColumn(t){this.nodes.push(new ir(t));}renameColumn(t,e){this.nodes.push(new lr(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new St(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ot([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new de(new F(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new de(new F("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??G(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new de(new F("unique",{columns:[t],constraintName:e?.constraintName??le(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=G(this.table,t,e);this.nodes.push(new be(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new N("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??le(this.table,t);this.nodes.push(new be(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new N("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new N("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new nt(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",o=this.sqlType==="mssql",n=this.sqlType==="oracledb";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new Le(t)):r?this.nodes.push(new Le(t)):o?this.nodes.push(new Le(t)):n&&this.nodes.push(new Le(t)),this)}};var Ie=class{constructor(t){if(this.sqlType=t||I.DB_TYPE,!this.sqlType)throw new N("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new $(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!ce.existsSync(t))throw new N("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=ht.basename(t),r=ht.extname(e);if(r!==".sql"&&r!==".txt")throw new N("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=ce.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new Ue(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?o.getMysqlOptions()||{}:{}},l=new mr(t,n,o.getNamedConstraints(),r?.ifNotExists,a),d=s.parse([l]).sql,u=d.startsWith("create table")?d:`create table ${d}`;this.rawQuery(u),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new br(t,r,this.sqlType);if(e(o),!r.length)return;let n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"}),s=[],a=()=>{if(!s.length)return;let d=new ge(t,s),u=n.parse([d]).sql;if(!u||!u.trim())return;let c=u.startsWith("alter table")?u:`alter table ${u}`;this.rawQuery(c),s=[];};for(let d of r)d.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(d);a();let l=r.filter(d=>d.file==="add_column").map(d=>d.column);this.generateAutoUpdateTriggers(t,l);}dropTable(t,e=false){let r=new cr(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new ge(t,[new Xe(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new st(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r={}){Array.isArray(e)||(e=[e]);let o=r.constraintName||io(t,e.join("_")),n=new fr(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new yr(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new ot(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addUnique(t,e,r){let o=Array.isArray(e)?e:[e],n=r?.constraintName??le(t,o.join("_")),s=new F("unique",{columns:o,constraintName:n}),a=new ge(t,[new de(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=G(t,e,r),n=new be(o),s=new ge(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?le(t,e.join("_")):le(t,e),n=r?.constraintName??o,s=new be(n),a=new ge(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new nt,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new F(...e),o=new ge(t,[new de(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new be(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addCheck(t,e,r){let o=r?.constraintName??`chk_${t}_custom`.substring(0,63),n=new F("check",{checkExpression:e,constraintName:o}),s=new ge(t,[new de(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){this.dropConstraint(t,e);}createExtension(t,e=true){let r=new pr(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(o=>o.folder==="column"&&o.autoUpdate===true).map(o=>q(o.column));for(let o of r){let n=this.getAutoUpdateTriggerSql(t,o);for(let s of n)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];case "oracledb":return [`CREATE OR REPLACE TRIGGER "${r}" BEFORE UPDATE ON "${t}" FOR EACH ROW BEGIN :NEW."${e}" := CURRENT_TIMESTAMP; END;`];default:return []}}generateAstInstance(t){return new b(t,this.sqlType)}};var Nr,yp,Tr=class{constructor(t,e){It(this,Nr);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new Ie(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=Ya(this,Nr,yp).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(`;
|
|
289
|
-
`)}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"}};Nr=new WeakSet,yp=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 wr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let d=l.getRelations();for(let u of d)u.type==="belongsTo"&&u.model().table===n.table&&a.push(`fk.${l.table}.${u.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(d=>d.table===n.table);if(l){let d=l.getColumns().find(u=>u.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let u=l.getRelations();for(let c of u)c.columnName===d.columnName&&a.push(`fk.${n.table}.${c.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let d of l)s(d);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),d=t.relationsToDrop?.find(u=>u.table===a&&u.relation.name===l);d&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:d,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(d)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let d of l)d.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):d.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(d=>d.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Sr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new wr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,o=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),n=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...o].filter(l=>n.has(l)));return e.filter(l=>{let d=r(l);return d?!(s.has(d)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new Ie(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(d=>d.table===o.table)?.getColumns().find(d=>d.columnName===o.columns[0])?.primaryKeyConstraintName||$e(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,d=>{let u=a||$e(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:u});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(u=>u.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}return e}computeFkConstraintName(t){let e=q(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=q(t.relation.manyToManyOptions.throughModel));let n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,G(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=q(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s=e[r.type](...o);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||$e(t,r.columnName)}),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new Ie(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=q(t.relation.manyToManyOptions.throughModel),r=q(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let o=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,n=q(r);if(t.relation.type==="belongsTo"){let m=t.relation.model(),p=m.primaryKey,h=m.getColumns().find(T=>T.columnName===p);if(h)n=h.databaseName;else {let T=m?.databaseCaseConvention||"preserve";n=U(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.model();if(typeof n=="string"&&n){let p=m.getColumns(),y=p.find(h=>h.columnName===n);if(y)n=y.databaseName;else {let h=m.primaryKey||"id",T=p.find(S=>S.columnName===h);if(T)n=T.databaseName;else {let S=m?.databaseCaseConvention||"preserve";n=U(n||h,S);}}}else {let p=m.primaryKey||"id",h=m.getColumns().find(T=>T.columnName===p);if(h)n=h.databaseName;else {let T=m?.databaseCaseConvention||"preserve";n=U(p,T);}}}let s=this.models.find(m=>m.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(m=>m.columnName===l);if(d)l=d.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=U(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=U(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.manyToManyOptions.leftForeignKey,p=q(m),y=a.find(h=>h.columnName===p);if(y)l=y.databaseName;else {let h=s?.databaseCaseConvention||"preserve";l=U(p,h);}}let u=t.relation.onDelete?.toLowerCase(),c=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,m=>{let p=o||G(t.table,l,e);m.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:u,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," "))}))}};function jf(i){return i.replace(/\s+/g," ").trim()}function Vf(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function De(i,t){let e=jf(t.toLowerCase()),r=Vf(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var Fe=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:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(u=>u?.type!==void 0&&u?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let c of n.indexes)o.indexes.map(m=>m.name).includes(c.name)||e.data.indexesToAdd.push({table:r.table,index:c.name});let u=r.getUniques?.()||[];for(let c of u)e.data.uniquesToAdd.push({table:r.table,name:c.name||"mandatory",columns:c.columns});for(let c of n.relations){if(c.type!=="belongsTo")continue;let m=q(c.constraintName);o.foreignKeys.find(y=>y.name===m)||e.data.relationsToAdd.push({table:r.table,relation:c,onDelete:c.onDelete,onUpdate:c.onUpdate});}return}for(let u of n.columns)o.columns.some(m=>m.name===u.databaseName||m.name===u.columnName)||e.data.columnsToAdd.push({table:r.table,column:u});for(let u of o.columns)n.columns.some(m=>m.databaseName===u.name||m.columnName===u.name)||e.data.columnsToDrop.push({table:r.table,column:u.name});for(let u of n.indexes)o.indexes.map(c=>c.name).includes(u.name)||e.data.indexesToAdd.push({table:r.table,index:u.name});let s=r.getUniques?.()||[];for(let u of s)o.indexes.some(m=>m.name===u.name&&m.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:u.name||"mandatory",columns:u.columns});let a=o.foreignKeys.map(u=>u.name);for(let u of o.indexes)u.isUnique||a.includes(u.name)||n.indexes.map(m=>m.name).includes(u.name)||e.data.indexesToDrop.push({table:r.table,index:u.name});for(let u of o.indexes){if(!u.isUnique||u.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(m=>m.name).includes(u.name)||e.data.uniquesToDrop.push({table:r.table,name:u.name});}for(let u of n.columns){let c=o.columns.find(y=>y.name===u.databaseName||y.name===u.columnName);if(!c)continue;let m=!e.areColumnsEqual(c,u,o.indexes),p=e.getDefaultChange({table:r.table,dbColumns:c,modelColumn:u});(m||p)&&e.data.columnsToModify.push({table:r.table,dbColumns:c,modelColumn:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;if(u.type==="manyToMany"&&u.manyToManyOptions){let p=q(u.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:p,relation:{type:"belongsTo",model:()=>r,columnName:q(u.manyToManyOptions.leftForeignKey),foreignKey:u.manyToManyOptions.leftForeignKey,constraintName:u.constraintName?q(u.constraintName):G(p,q(u.manyToManyOptions.leftForeignKey||Pe(r.table)),r.table),onDelete:u.onDelete,onUpdate:u.onUpdate},onDelete:u.onDelete,onUpdate:u.onUpdate});continue}let c=q(u.constraintName);if(c&&o.foreignKeys.some(p=>p.name===c))continue;o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,u,p))||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let l=new Set(n.relations.filter(u=>u.type==="belongsTo").map(u=>{let c=q(u.foreignKey)||u.columnName,p=r.getColumns().find(y=>y.columnName===c)?.databaseName||c;return q(u.constraintName)||G(r.table,p,u.model().table)}));for(let u of o.foreignKeys){if(u.name&&l.has(u.name))continue;n.relations.find(m=>m.type!=="belongsTo"&&m.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,m,u))||e.data.relationsToDrop.push({table:r.table,relation:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;let c=o.foreignKeys.find(m=>e.relationMatchesDbRelation(r,u,m));c&&!e.areRelationsEqual(c,u)&&e.data.relationsToModify.push({table:r.table,dbRelation:c,modelRelation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let d=r.primaryKey;if(d&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[d]}),o.primaryKey&&!d&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),d&&o.primaryKey){let u=r.getColumns().find(c=>c.columnName===d);u&&!e.arePrimaryKeysEqual(o.primaryKey,u)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:d});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getSqlStatementsByPhase(){let t=new Sr(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),o={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let n of r)o[n.phase].push(...n.sqlStatements);return o}areColumnsEqual(t,e,r=[]){let o=t.name===e.databaseName,n=this.sql.getDbType(),s=De(n,t.dataType),a=typeof e.type=="string"?De(n,e.type):void 0;a&&o&&(o=s===a),e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,u=t.isNullable;o=o&&d===u;}return o}areRelationsEqual(t,e){let r=q(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),u=d.primaryKey||"id",c=d.getColumns().find(y=>y.columnName===u),m=d.table,p=c?.databaseName||u;o=o&&t.referencedTable===m&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=q(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===d;}let n=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&o&&(o=n===a),l&&o&&(o=s===l),o}relationMatchesDbRelation(t,e,r){let o,n=e;if(n&&n.model){if(typeof n.model=="function"&&n.model.table)o=n.model;else if(typeof n.model=="function")try{let h=n.model();h&&h.table&&(o=h);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?q(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=q(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),u=(n.type||"belongsTo")==="belongsTo"?q(n.foreignKey):n.columnName,c=l.find(h=>h.columnName===u);c&&(u=c.databaseName);let m=o.primaryKey||"id",y=o.getColumns().find(h=>h.columnName===m)?.databaseName||m;return r.columns.length===1&&r.columns[0]===u&&r.referencedColumns.length===1&&r.referencedColumns[0]===y}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=De(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?De(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",d=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&d?false:"drop";if(s&&a){let u=String(t.dbColumns.defaultValue),c=String(t.modelColumn.constraints?.default),m=this.normalizeDefaultValue(e,r,u),p=this.normalizeDefaultValue(e,o||r,c);return m!==p?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=q(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(D=>D.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",u=s.getColumns().find(D=>D.columnName===l),c=a.getColumns().find(D=>D.columnName===d);if(!u||!c)continue;let m=q(o.manyToManyOptions.leftForeignKey)||l,p=q(o.manyToManyOptions.rightForeignKey)||d,y=await this.sql.getTableSchema(n);if(!y.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(u,m),this.clonePkAsColumn(c,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:m,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let h=this.clonePkAsColumn(u,m),T=this.clonePkAsColumn(c,p),S=y.columns.find(D=>D.name===m),M=y.columns.find(D=>D.name===p),x=S?this.areColumnsEqual(S,h,y.indexes):false,_=M?this.areColumnsEqual(M,T,y.indexes):false;for(let D of y.foreignKeys){let Y=D.referencedTable===s.table,Z=D.referencedTable===a.table;if(!Y&&!Z)continue;let Te=Y?m:p,_e=D.columns[0];_e&&_e!==Te&&(this.data.relationsToDrop.push({table:n,relation:D}),_e!==m&&_e!==p&&this.data.columnsToDrop.push({table:n,column:_e}));}let P={};x||(P[h.databaseName]=h),_||(P[T.databaseName]=P[T.databaseName]||T);for(let D of Object.keys(P))this.data.columnsToAdd.push({table:n,column:P[D]});let O=this.buildBelongsToRelation(n,()=>s,m,l,void 0,o.onDelete,o.onUpdate),R=this.buildBelongsToRelation(n,o.model,p,d,void 0,o.onDelete,o.onUpdate),Q=y.foreignKeys.find(D=>D.referencedTable===s.table&&D.columns.length===1&&D.columns[0]===m),ke=y.foreignKeys.find(D=>D.referencedTable===a.table&&D.columns.length===1&&D.columns[0]===p);if(!Q){let D=y.foreignKeys.find(Y=>Y.referencedTable===s.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(O);}if(!ke){let D=y.foreignKeys.find(Y=>Y.referencedTable===a.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(R);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,u=o.getColumns().find(m=>m.columnName===l)?.databaseName||l,c=q(a.constraintName)||G(o.table,u,a.model().table);s.add(c);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(h=>h.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let d=o.table,u=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let h=o.relation.model();d=h.table;let T=h.primaryKey||"id";u=h.getColumns().find(M=>M.columnName===T)?.databaseName||T;}let c=new Set([l,o.relation.columnName].filter(Boolean)),m=n.foreignKeys.some(h=>{if(h.columns.length!==1||h.referencedColumns.length!==1)return false;let T=c.has(h.columns[0]),S=h.referencedTable===d,M=h.referencedColumns[0]===u;return T&&S&&M}),p=q(o.relation.constraintName)||G(o.table,l,d),y=e.get(o.table)||new Set;if(m||p&&y.has(p))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let h=q(o.relation.manyToManyOptions.throughModel),T=q(o.relation.manyToManyOptions.leftForeignKey),S=q(o.relation.manyToManyOptions.rightForeignKey),M=o.table===h&&o.relation.columnName===T&&o.relation.model().table===s?.table,x=o.table===h&&o.relation.columnName===S&&o.relation.model().table!==s?.table,_=await this.sql.getTableSchema(h),P=_.foreignKeys.some(R=>R.columns.length===1&&R.columns[0]===T&&R.referencedTable===(s?.table||"")),O=_.foreignKeys.some(R=>R.columns.length===1&&R.columns[0]===S&&R.referencedTable===o.relation.model().table);if(M&&P||x&&O)return null}return o})).then(o=>o.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async o=>{let n=this.models.find(d=>d.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(d=>{if(d.type!=="belongsTo")return false;let c=a.find(T=>T.columnName===d.foreignKey)?.databaseName||d.foreignKey,m=d.model(),p=m.primaryKey||"id",h=m.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===c&&o.relation.referencedTable===m.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===h})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?q(n):G(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 at=class extends w{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var K=class extends w{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var H=class extends w{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var ue=class extends w{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Se=class extends w{constructor(e,r=[],o=[],n=false){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o;}};var C=class extends w{constructor(e,r,o=false,n,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=o,this.operator=n,this.value=s;}};var Ee=class extends w{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var oe=class extends C{constructor(e,r,o=false,n,s,a=false){super(e,r,o,"=",s,a);this.file="where_json";this.jsonOperator=n,this.value=s;}};var qe=class extends w{constructor(e,r,o,n="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=o,this.chainsWith=` ${n}`;}};var Jf=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,Hf=/^\d{4}-\d{2}-\d{2}$/,Ua=i=>typeof i!="string"?i:Jf.test(i)?new Date(i.replace(" ","T")+"Z"):Hf.test(i)?new Date(i+"T00:00:00Z"):i,Yf=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),gp=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Yf(r):t[e]=r;}return t};var qr=class extends Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:d=>{s=true,a=d;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(d=>{r=true,this.emit("error",d);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},bp=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((d,u)=>{n.run(i,t,function(c){c&&u(c),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,u)=>{n.all(i,t,(c,m)=>{c&&u(c),(!m||!m.length)&&d([]),d(m);});});let s=r?.typeofModel;if(!s)return new Promise((d,u)=>{n.run(i,t,function(c){c?u(new Error(c.message)):d(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((c,m)=>{n.run(i,t,function(p){if(p)return m(p);let y=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){c([y]);return}let h=y?.[a]||this.lastID;if(!h)return m(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[h],(S,M)=>{if(S)return m(S);c([M]);});});});if(!Array.isArray(r.models))throw new N("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models;if(!a)return new Promise((c,m)=>{n.run(i,t,function(p){if(p)return m(p);c(d);});});let u=[];return new Promise(async(c,m)=>{try{let p=d.map(async y=>{let h=new f(s),{columns:T,values:S}=await h.prepareColumns(Object.keys(y),Object.values(y),"insert"),M=Object.fromEntries(T.map((O,R)=>[O,S[R]])),x=new b(s,e.getDbType()),{sql:_,bindings:P}=x.parse([new H(new K(s.table),[M])]);return new Promise((O,R)=>{n.run(_,P,function(Q){if(Q)return R(Q);let ke=y[a]||this.lastID;if(!ke)return R(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let D=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(D,[ke],(Y,Z)=>{if(Y)return R(Y);O(Z);});});})});u=await Promise.all(p),c(u);}catch(p){m(p);}})}return new Promise((d,u)=>{n.run(i,t,function(c){c?u(new Error(c.message)):d(this.changes);});})};var j=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||ee(i,e.logs,t),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await Mt(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),d=0,u=i.replace(/\?/g,()=>`$${++d}`),c=await Mt(()=>l.query(u,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?c.rows:o==="raw"?c:c.rowCount;case "sqlite":let m=await Mt(()=>bp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(m)?m:[m]:m;case "mssql":let p=e.getPool(),y=e.sqlConnection?e.sqlConnection.request():p.request();t.forEach((P,O)=>{y.input(`p${O}`,P);});let h=0,T=i.replace(/\?|@(\d+)/g,()=>`@p${h++}`),S=await Mt(()=>y.query(T),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?S.rowsAffected[0]:o==="raw"?S:S.recordset;case "oracledb":let M=4002,x=null,_=!!e.sqlConnection;try{x=e.sqlConnection?e.sqlConnection:await e.getConnection();let P=t.map(Ua),O=0,R=i.replace(/\?/g,()=>`:${++O}`),Q=await Mt(()=>x.execute(R,P,{outFormat:M,autoCommit:!_}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?Q.rowsAffected:o==="raw"?Q:await Promise.all(Q.rows?.map(async D=>{let Y=await gp(D),Z={};for(let Te in Y)Z[Te.toLowerCase()]=Y[Te];return Z})??[])}finally{x&&!_&&await x.close();}default:throw new N("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},_r=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),c=0,m=false,p=false,y=()=>{try{a.release();}catch{}};return u.on("data",h=>{if(o.onData){c++,Promise.resolve(o.onData(l,h)).then(()=>{c--,m&&c===0&&!p&&(y(),l.end());}).catch(T=>{p=true,y(),l.destroy(T);});return}l.write(h);}),u.on("end",()=>{m=true,c===0&&!p&&(y(),l.end());}),u.on("error",h=>{p=true,y(),l.destroy(h);}),l.on("close",()=>{y();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new B("pg-query-stream")}),d=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),u=0,c=i.replace(/\?/g,()=>`$${++u}`),m=new l.default(c,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(m),y=0,h=false,T=false,S=M=>{try{a.release(M);}catch{}};return p.on("data",M=>{if(o.onData){y++,Promise.resolve(o.onData(d,M)).then(()=>{y--,h&&y===0&&!T&&(S(),d.end());}).catch(x=>{T=true,S(x),d.destroy(x);});return}d.write(M);}),p.on("end",()=>{h=true,y===0&&!T&&(S(),d.end());}),p.on("error",M=>{T=true,S(M),d.destroy(M);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new qr(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((y,h)=>{l.input(`p${h}`,y);});let d=0,u=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),c=0,m=false,p=false;return l.on("row",y=>{if(!p){if(o.onData){c++,Promise.resolve(o.onData(a,y)).then(()=>{c--,m&&c===0&&!p&&a.end();}).catch(h=>{p=true,a.destroy(h);});return}a.write(y);}}),l.on("error",y=>{p=true,a.destroy(y);}),l.on("done",()=>{m=true,c===0&&!p&&a.end();}),l.query(u),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=4002,u=0,c=i.replace(/\?/g,()=>`:${++u}`),m=t.map(Ua),p=a.queryStream(c,m,{outFormat:d}),y=0,h=false,T=false,S=async()=>{try{await a.close();}catch{}};return p.on("data",M=>{if(T)return;let x={};for(let _ in M)x[_.toLowerCase()]=M[_];if(o.onData){y++,Promise.resolve(o.onData(l,x)).then(()=>{y--,h&&y===0&&!T&&(S(),l.end());}).catch(_=>{T=true,S(),l.destroy(_);});return}l.write(x);}),p.on("end",()=>{h=true,y===0&&!T&&(S(),l.end());}),p.on("error",M=>{T=true,S(),l.destroy(M);}),l}default:throw new N("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function Mt(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,Ga(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var L=(i,t="millis",e=3)=>async(...r)=>{let o=performance.now(),n=await i(...r),s=performance.now()-o;return [(t==="millis"?s:s/1e3).toFixed(e),n]};var _t=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Ht(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new N("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Cr(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function Tp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var lt=i=>typeof i=="number"?i:parseFloat(i);var ie=class extends w{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var je=class extends w{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var Rr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var xr=class extends w{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var ve=class extends w{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var ne=class extends w{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var Ct=class extends w{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var Ar=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var Pr=class extends w{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Rt=class extends w{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var $r=class{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs;let r=this.model?.getColumns;this.modelColumns=typeof r=="function"?r.call(this.model):[],this.modelColumnsMap=new Map(this.modelColumns.map(o=>[o.columnName,o]));}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new Ct(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Ct(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Rt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Rt(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 Ar(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new Pr(t),this}};var Ve=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new C(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new C(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 C(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new C(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 C(t,"and",false,"in",e)),this):(this.whereNodes.push(new C("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new C(t,"or",false,"in",e)),this):(this.whereNodes.push(new C("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new C(t,"and",true,"in",e)),this):(this.whereNodes.push(new C("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new C(t,"or",true,"in",e)),this):(this.whereNodes.push(new C("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new C(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new C(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new C(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new C(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 C(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 C(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 C(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 C(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 Ee(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 Ee(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new C(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new C(t,"or",true,"=",e??[],true)),this}};var Or=class extends $r{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ne(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ne(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ne(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ne(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ne(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ne(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,d)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,d)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,d)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,d)),this}};var Ir=class extends Or{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new K(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=U(s,this.model.databaseCaseConvention);this.selectNodes.push(new ie(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=U(o,this.model.databaseCaseConvention);this.selectNodes.push(new ie(n));}),this}selectRaw(e){return this.selectNodes.push(new ie(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":U(r,this.model.databaseCaseConvention);return this.selectNodes.push(new ie(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new K(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}from(e){return this.fromNode=new K(e),this}table(e){return this.fromNode=new K(e),this}distinct(){return this.distinctNode=new Rr,this}distinctOn(...e){return this.distinctOnNode=new xr(e),this}selectJson(e,r,o){return this.selectNodes.push(new ve(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new ve(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new ve(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new ve(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new ve(e,"",r,"raw",true)),this}};var Dr=class extends Ir{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof k&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof k||typeof o=="function")?this.andWhereSubQuery(e,r,o):this.andWhere(e,r,o)}andWhere(e,r,o){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof k&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",false,n,s)),this}orWhere(e,r,o){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof k&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"or",false,n,s)),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof k&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",true,n,s)),this}andWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof k&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",true,n,s)),this}orWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof k&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"or",true,n,s)),this}whereBetween(e,r,o){return this.andWhereBetween(e,r,o)}andWhereBetween(e,r,o){return this.whereNodes.push(new C(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new C(e,"or",false,"between",[r,o])),this}whereNotBetween(e,r,o){return this.andWhereNotBetween(e,r,o)}andWhereNotBetween(e,r,o){return this.whereNodes.push(new C(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new C(e,"or",true,"between",[r,o])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"and",false,"in",r)),this):(this.whereNodes.push(new C("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"or",false,"in",r)),this):(this.whereNodes.push(new C("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 C(e,"and",true,"in",r)),this):(this.whereNodes.push(new C("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"or",true,"in",r)),this):(this.whereNodes.push(new C("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new C(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new C(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new C(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new C(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(e,"and",false,o?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new C(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new C(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new je(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new je(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new je(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new je(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof k)return e;let r=new k(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new qe(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new qe(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new k(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ee(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new k(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ee(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Er=class extends Dr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new oe(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new oe(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new oe(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new oe(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new oe(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new oe(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new oe(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new oe(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new oe(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new oe(t,"or",false,"raw",e)),this}};var k=class i extends Er{constructor(e,r=Ae.instance){super(e,r);this.isNestedCondition=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new b(this.model,this.dbType),this.interpreterUtils=new f(this.model);}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource);return r(n),this.selectNodes.push(new ie(n.extractQueryNodes(),o)),this}return this.selectNodes.push(new ie(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>j(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new N("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await _r(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let s=await this.many(),a=await n.getCount(),l=s[s.length-1],d=l?l[r.discriminator]:null;return [{paginationMetadata:Tp(e,a),data:s},{key:r.discriminator,value:d}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new qt("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new qt("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new We(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new We(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new We(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new We(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:Cr(e,r,a),data:s}}from(e,r){if(typeof e=="function"){if(!r)throw new N("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new K(n,r),this}return this.fromNode=new K(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("normal",e,n)),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new N("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("materialized",e,n)),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new H(this.fromNode,[o],r,n),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((p,y)=>[p,a[y]]));this.insertNode=new H(this.fromNode,[l],r,n);let{sql:d,bindings:u}=this.astParser.parse([this.insertNode]),c=await this.getSqlDataSource("write"),m=await j(d,u,c,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(m)&&m.length?m[0]:m})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new H(this.fromNode,o,r,n),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async c=>{let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert");return Object.fromEntries(m.map((y,h)=>[y,p[h]]))}));this.insertNode=new H(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await this.getSqlDataSource("write"),u=await j(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return u})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new H(new K(this.model.table),[a],void 0,true),this.onDuplicateNode=new ue(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),u=Object.fromEntries(l.map((h,T)=>[h,d[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([u],s,n,o,[e]);let{sql:c,bindings:m}=this.astParser.parse([new H(new K(this.model.table),[u],void 0,true),new ue(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),y=await j(c,m,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(y)?y:[y]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new H(new K(this.model.table),s,void 0,true),this.onDuplicateNode=new ue(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async m=>{let{columns:p,values:y}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert"),h=Object.fromEntries(p.map((T,S)=>[T,y[S]]));a.push(h);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:d}=this.astParser.parse([new H(new K(this.model.table),a,void 0,true),new ue(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),u=await this.getSqlDataSource("write"),c=await j(l,d,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(c)?c:[c]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),d=Q=>this.interpreterUtils.formatStringColumn("mssql",Q),u=[],c=e.map(Q=>`select ${a.map(D=>(u.push(Q[D]),`@${u.length}`)).join(", ")}`),m=a.map(d).join(", "),p=c.join(" union all "),y=r.map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(" and "),h=o.filter(Q=>!r.includes(Q)).map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(", "),T=a.map(d).join(", "),S=a.map(Q=>`source.${d(Q)}`).join(", "),M=n.returning&&n.returning.length?n.returning.map(Q=>`inserted.${d(Q)}`).join(", "):a.map(Q=>`inserted.${d(Q)}`).join(", "),_=(n.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",P=`merge into ${l} as target using (${p}) as source (${m}) on ${y} ${_} when not matched then insert (${T}) values (${S}) output ${M};`,O=await this.getSqlDataSource("write"),R=await j(P,u,O,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(R)?R:[R]}update(e){let r=Object.keys(e),o=Object.values(e);return this.updateNode=new Se(this.fromNode,r,o),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new Se(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return j(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}truncate(){return this.truncateNode=new st(this.fromNode),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await j(e,r,o,this.dbType,"rows");})}delete(){return this.deleteNode=new at(this.fromNode),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),o=await this.getSqlDataSource("write");return j(e,r,o,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=et()}=e||{};return this.updateNode=new Se(this.fromNode,[r],[o]),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Se(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return j(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return Ze(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new ie("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=xe(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=V(this.modelSelectedColumns),e.distinctNode=V(this.distinctNode),e.distinctOnNode=V(this.distinctOnNode),e.selectNodes=V(this.selectNodes),e.withQuery=V(this.withQuery),e.joinNodes=V(this.joinNodes),e.whereNodes=V(this.whereNodes),e.groupByNodes=V(this.groupByNodes),e.havingNodes=V(this.havingNodes),e.orderByNodes=V(this.orderByNodes),e.lockQueryNodes=V(this.lockQueryNodes),e.unionNodes=V(this.unionNodes),e.withNodes=V(this.withNodes),e.fromNode=V(this.fromNode),e.limitNode=V(this.limitNode),e.offsetNode=V(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.from(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new ie("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}async manyWithPerformance(e="millis"){let[r,o]=await L(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await L(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await L(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await L(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await L(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await L(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await L(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};var dt=class i extends k{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.sqlModelManagerUtils=new _t(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=new Map,this.modelColumnsDatabaseNames=new Map,this.model.getColumns().forEach(n=>{this.modelColumnsMap.set(n.databaseName,n),this.modelColumnsDatabaseNames.set(n.databaseName,n.columnName);});}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){return r.connection?new i(e,r.connection):r.trx?new i(e,r.trx.sql):new i(e,e.sqlInstance)}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new N(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a,this.model));if(!o.length)return [];let n=await ye(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsRecursively(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await _r(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),u=await ye([d],this.model,this.modelSelectedColumns);u&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([u]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new N(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(...e){return this.model.insert(...e)}insertMany(...e){return this.model.insertMany(...e)}upsert(...e){return this.model.upsert(...e)}upsertMany(...e){return this.model.upsertMany(...e)}update(e,r={}){let o=super.update(e);return new J(()=>o.unWrap(),()=>o.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),o))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new J(()=>r.unWrap(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=super.delete();return new J(()=>r.unWrap(),()=>r.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),r))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,d]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:Cr(e,r,d),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof k)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r){let o=this.sqlModelManagerUtils.getRelationFromModel(e),n=new i(o.model,this.sqlDataSource);return n.relation=o,r?.(n),this.relationQueryBuilders.push(n),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereExists(u),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereExists(u),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereNotExists(u),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereNotExists(u),this}clone(){let e=super.clone();return e.relationQueryBuilders=V(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(m=>{let p=m[e.foreignKey];p&&n.set(String(p),m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=null;return}let y=n.get(String(p));m[e.columnName]=y||null;});break;case "belongsTo":let s=new Map;o.forEach(m=>{if(!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=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 y=s.get(String(p));m[e.columnName]=y||null;});break;case "hasMany":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(m=>{let p=m[e.foreignKey];if(!p)return;let y=String(p);a.has(y)||a.set(y,[]),a.get(y).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let y=a.get(String(p))||[];m[e.columnName]=y;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,u=l.leftForeignKey,c=this.modelColumnsMap.get(u)||this.modelColumnsDatabaseNames.get(u)||U(u,this.model.modelCaseConvention);o.forEach(m=>{let p=m[c];if(p==null)return;let y=String(p);d.has(y)||d.set(y,[]),delete m[c],d.get(y).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let y=d.get(String(p))||[];m[e.columnName]=y;});break;default:throw new N(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=Ne.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,u=e.orderByNodes.map(R=>R.isRawValue?R.column:`${this.interpreterUtils.formatStringColumn(this.dbType,R.column)} ${R.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let c=e.with(d,R=>R.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${u}) as rn_${l}`).whereIn(r.foreignKey,n));s&&c.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&c.whereRaw(`rn_${l} > ${a}`);let m=e.modelSelectedColumns.map(R=>so(R,d,e.model.table));return c.select(...m).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new N(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let y=e.limitNode?.limit,h=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(R=>R.includes(".")?R:`${r.model.table}.${R}`):[`${r.model.table}.*`];if(!y&&!h)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let S=Ne.randomBytes(6).toString("hex"),M=`${r.model.table}_cte_${S}`,x=e.orderByNodes.map(R=>{if(R.isRawValue)return R.column;let Q=R.column.includes(".")?R.column:`${r.model.table}.${R.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,Q)} ${R.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let _=`${Ne.randomBytes(6).toString("hex")}_left_foreign_key`,P=e.with(M,R=>R.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,_]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${x}) as rn_${S}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));y&&P.whereRaw(`rn_${S} <= ${y+(h||0)}`),h&&P.whereRaw(`rn_${S} > ${h}`);let O=T.map(R=>so(R,M,e.model.table));return P.select(...O).select([`${M}.${_}`,p.leftForeignKey]).from(M);default:throw new N(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new f(r.model),a=new f(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),u=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let d=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),u=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let d=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new N(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===d.throughModel&&p.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let c=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${c} = ${m}`),o&&typeof n=="number"&&e.groupByRaw(c).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new N(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={};return Object.entries(e).forEach(([n,s])=>{if(this.modelColumnsDatabaseNames.get(n)){o[n]=s;return}o[n]=s;}),o}async manyWithPerformance(e={},r="millis"){let[o,n]=await L(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await L(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await L(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await L(this.paginate.bind(this,e,r,{ignoreHooks:s}),n)();return {data:{paginationMetadata:l.paginationMetadata,data:l.data},time:Number(a)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await L(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var xt=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=wl(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new f(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new N(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new N(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(l=>[l,t[l]])),o=!e.returning||e.returning.length===0,n=new H(new K(this.model.table),[r],e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:xe(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return Ze(l,d)};return new J(s,a,async()=>{e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),u={};l.forEach((S,M)=>{let x=d[M];u[S]=x,t[S]??(t[S]=x);});let c=!e.returning||e.returning.length===0,{sql:m,bindings:p}=this.astParser.parse([new H(new K(this.model.table),[u],e.returning,c)]),y=await j(m,p,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let h=y[0];return h?(await this.model.afterFetch?.([h]),await ye([h],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(l=>Object.fromEntries(Object.keys(l).map(d=>[d,l[d]]))),o=!e.returning||e.returning.length===0,n=new H(new K(this.model.table),r,e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:xe(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return Ze(l,d)};return new J(s,a,async()=>{if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let h=this.model.primaryKey,T=Object.keys(t[0]||{});if(h&&!T.includes(h))return this.handleOracleIdentityInsert(t,e)}let l=[];for(let h of t){let{columns:T,values:S}=await this.interpreterUtils.prepareColumns(Object.keys(h),Object.values(h),"insert"),M={};T.forEach((x,_)=>{let P=S[_];M[x]=P,h[x]??(h[x]=P);}),l.push(M);}let d=!e.returning||e.returning.length===0,{sql:u,bindings:c}=this.astParser.parse([new H(new K(this.model.table),l,e.returning,d)]),m=await j(u,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(m,t,"many",e.returning)||[];let p=m;return p.length?(await this.model.afterFetch?.(p),await ye(p,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(u=>Object.fromEntries(Object.keys(u).map(c=>[c,u[c]]))),s=new H(new K(this.model.table),n,void 0,true),a=new ue(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning),l=()=>{let u=this.astParser.parse([s,a]);return {sql:xe(this.sqlDataSource,u.sql),bindings:u.bindings}},d=()=>{let{sql:u,bindings:c}=l();return Ze(u,c)};return new J(l,d,async()=>{let u=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async y=>{let{columns:h,values:T}=await this.interpreterUtils.prepareColumns(Object.keys(y),Object.values(y),"insert"),S=Object.fromEntries(h.map((M,x)=>[M,T[x]]));u.push(S);})),this.sqlType==="mssql")return this.executeMssqlMerge(u,t,e,o,r);let{sql:c,bindings:m}=this.astParser.parse([new H(new K(this.model.table),u,void 0,true),new ue(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await j(c,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=O=>this.interpreterUtils.formatStringColumn("mssql",O),d=[],u=t.map(O=>`select ${s.map(Q=>(d.push(O[Q]),`@${d.length}`)).join(", ")}`),c=s.map(l).join(", "),m=u.join(" union all "),p=e.map(O=>`target.${l(O)} = source.${l(O)}`).join(" and "),y=r.filter(O=>!e.includes(O)).map(O=>`target.${l(O)} = source.${l(O)}`).join(", "),h=s.map(l).join(", "),T=s.map(O=>`source.${l(O)}`).join(", "),S=o.returning&&o.returning.length?o.returning.map(O=>`inserted.${l(O)}`).join(", "):s.map(O=>`inserted.${l(O)}`).join(", "),x=(o.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",_=`merge into ${a} as target using (${m}) as source (${c}) on ${p} ${x} when not matched then insert (${h}) values (${T}) output ${S};`;return await j(_,d,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}})}async updateRecord(t,e){let r=new Set(this.model.getColumns().map(p=>p.columnName)),o=Object.keys(t).filter(p=>r.has(p)),n=o.map(p=>t[p]),{columns:s,values:a}=await this.interpreterUtils.prepareColumns(o,n,"update"),{primaryKey:l}=this.model;if(!l)throw new N(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=s.indexOf(l);d!==-1&&(s.splice(d,1),a.splice(d,1));let{sql:u,bindings:c}=this.astParser.parse([new Se(new K(this.model.table),s,a),new C(l,"and",false,"=",t[l])]);await j(u,c,this.sqlDataSource,this.sqlType,"affectedRows");let m=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!m)throw new N(this.model.name+"::updateRecord","ROW_NOT_FOUND");return m}async deleteRecord(t){if(!this.model.primaryKey)throw new N(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new C(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new at(new K(this.model.table)),e]);await j(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new dt(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await ye([a],this.model):null}return await ye(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(u=>u[this.model.primaryKey]),l=a.map(u=>`'${u}'`).join(","),d=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?d.length?d[0]:null:d}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,y)=>{let h=a[y];l[p]=h,n[p]??(n[p]=h);});let{sql:d,bindings:u}=this.astParser.parse([new H(new K(this.model.table),[l],e.returning)]);await j(d,u,this.sqlDataSource,this.sqlType,"rows");let c=this.query().select(...e.returning||["*"]);for(let[p,y]of Object.entries(l))y!=null&&p!==o&&c.where(p,"=",y);o&&c.orderBy(o,"desc");let m=await c.one({ignoreHooks:["beforeFetch"]});m?(o&&m[o]&&(n[o]=m[o]),r.push(m)):r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let d of n)this.handleWhereCondition(a,d,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,d]=a;o?t.orWhereBetween(e,l,d):t.whereBetween(e,l,d);break}case "$not between":{let[l,d]=a;o?t.orWhereNotBetween(e,l,d):t.whereNotBetween(e,l,d);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Np=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??et()});var At=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Ne.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{await t(e),await e.commit();}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),ee("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;ee("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":ee("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;ee("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":ee("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":ee("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;ee("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":ee("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new N("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){g.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new N("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new N("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw g.error(e),new B("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new N("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var me,Me=class Me extends Ft{constructor(e){super(e);this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new Ut;this.migrationConfig={path:I.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:zr(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new Me(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static get instance(){if(!Qe(this,me))throw new N("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return Qe(this,me)}static async connectToSecondarySource(e,r){let o=new Me(e);await o.connectWithoutSettingPrimary();let n=o;return await r?.(n),n}static async useConnection(e,r){let o=new Me(e);await o.connectWithoutSettingPrimary();let n=o;try{await r(n),o.isConnected&&await o.disconnect();}catch(s){throw o.isConnected&&await o.disconnect(),s}}static async disconnect(){if(!Qe(this,me)){g.warn("Connection already closed");return}await Qe(this,me).disconnect(),Fr(this,me,null);}static async startGlobalTransaction(e){return this.instance.startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.instance.commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.instance.rollbackGlobalTransaction();}static get isInGlobalTransaction(){return !!Qe(this,me)?.globalTransaction}async connect(){if(Qe(Me,me))throw new N("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await Be(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await Be(e.sqlType,e.inputDetails),e.ownsPool=true;})),Fr(Me,me,this);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){return this._models}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new N("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new N("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,d=[];a?(l=r,d=o):(l=void 0,d=r!==void 0?[r,...o]:o);let u=Gr(JSON.stringify(d)),c=u?`${e}:${u}`:e,m=await this.cacheAdapter.get(c);if(m!==void 0)return m;let p=await n(...d);return await this.cacheAdapter.set(c,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new N("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Gr(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new Me(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await Be(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new k(Np(e,r),o);return r?.alias&&n.from(e,r.alias),n}from(e){return new dt(e,this)}schema(){if(!this.isConnected)throw new N("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Tr(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new At(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new N("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive){if(typeof e=="function")try{await this.globalTransaction.nestedTransaction(e);return}catch(l){throw l}return await this.globalTransaction.nestedTransaction()}let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new At(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{await e(s),await s.commit({throwErrorOnInactiveTransaction:!1});return}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected)throw new N("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new xt(e,this.globalTransaction.sql):new xt(e,this)}getPool(){if(!this.sqlPool)throw new N("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new N("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");switch(this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new N("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){ee("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),ee("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new N("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){g.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await Fe.makeDiff(this)).getSqlStatements();if(!o.length){g.info("No new changes detected between database schema and models metadata");return}if(g.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);g.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),g.info(`Synced schema with ${o.length} SQL statements`);}extractRowsFromRawResult(e){let r=this.getDbType();if(r==="mysql"||r==="mariadb"){if(Array.isArray(e)&&e.length>=1){let o=e[0];if(Array.isArray(o))return o;if(typeof o=="object"&&o!==null&&("insertId"in o||"affectedRows"in o))return []}return e}return r==="postgres"||r==="cockroachdb"?e&&typeof e=="object"&&"rows"in e?e.rows||[]:e:Array.isArray(e)?e:[]}async rawQuery(e,r=[],o){if(!this.isConnected)throw new N("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let n=xe(this,e);return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async a=>j(n,r,a,this.getDbType(),"raw")):j(n,r,this,this.getDbType(),"raw")}rawStatement(e){return new $(e)}async getTableSchema(e){let[r,o,n,s]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e)]);return {columns:r,indexes:o,foreignKeys:n,primaryKey:s}}getModelOpenApiSchema(){return al(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new N("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Yr(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new N("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await il(this,this.adminJsOptions),this.adminJsInstance)}getAdminJs(){return this.adminJsInstance}getAdminJsOptions(){return this.adminJsOptions}isAdminJsEnabled(){return !!this.adminJsOptions?.enabled}async getTableInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new or(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(Tt(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=De(s,l);return {name:a.name,dataType:d,isNullable:a.notnull===0,defaultValue:a.dflt_value??null,withTimezone:null}}):n.map(a=>{let l=String(a.column_name||a.COLUMN_NAME||a.name||""),d=String(a.data_type||a.DATA_TYPE||a.type||"").toLowerCase(),u=De(s,d),c=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,m=typeof c=="string"?c.toLowerCase()!=="no":typeof c=="boolean"?c:a.notnull!==void 0?a.notnull===0:true,p=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,y=a.char_length!=null?Number(a.char_length):null,h=a.numeric_precision!=null?Number(a.numeric_precision):null,T=a.numeric_scale!=null?Number(a.numeric_scale):null,S=a.timezone!=null?!!a.timezone:/with time zone/.test(String(a.column_type||a.udt_name||d||"").toLowerCase());return {name:l,dataType:u,isNullable:m,defaultValue:p,length:y,precision:h,scale:T,withTimezone:S}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new tr(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(Tt(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let u=d.Key_name,c=d.Non_unique===0,m=l.get(u)||{name:u,columns:[],isUnique:c};m.columns.push(d.Column_name),l.set(u,m);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let u=d.index_name,c=!!d.is_unique,m=l.get(u)||{name:u,columns:[],isUnique:c};m.columns.push(d.column_name),l.set(u,m);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,u=!!l.unique,c=await this.rawQuery(`PRAGMA index_info(${d})`),p=this.extractRowsFromRawResult(c).map(y=>y.name);a.push({name:d,columns:p,isUnique:u});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new er(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Tt(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let u=Number(d.id),c=l.get(u)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};c.columns.push(String(d.from)),c.referencedColumns.push(String(d.to)),l.set(u,c);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),u=d||`${l.referenced_table}_${l.column_name}`,c=a.get(u)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};c.columns.push(String(l.column_name)),c.referencedColumns.push(String(l.referenced_column)),a.set(u,c);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new rr(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Tt(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
|
|
289
|
+
`)}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"}};Nr=new WeakSet,yp=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 wr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let d=l.getRelations();for(let u of d)u.type==="belongsTo"&&u.model().table===n.table&&a.push(`fk.${l.table}.${u.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(d=>d.table===n.table);if(l){let d=l.getColumns().find(u=>u.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let u=l.getRelations();for(let c of u)c.columnName===d.columnName&&a.push(`fk.${n.table}.${c.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let d of l)s(d);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),d=t.relationsToDrop?.find(u=>u.table===a&&u.relation.name===l);d&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:d,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(d)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let d of l)d.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):d.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(d=>d.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var Sr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.models),this.dropResolver=new wr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,o=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),n=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...o].filter(l=>n.has(l)));return e.filter(l=>{let d=r(l);return d?!(s.has(d)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new Ie(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(d=>d.table===o.table)?.getColumns().find(d=>d.columnName===o.columns[0])?.primaryKeyConstraintName||$e(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,d=>{let u=a||$e(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:u});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(u=>u.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}return e}computeFkConstraintName(t){let e=q(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=q(t.relation.manyToManyOptions.throughModel));let n=this.models.find(a=>a.table===t.table)?.getColumns()||[],s=t.relation.columnName;return t.relation.type==="belongsTo"?s=n.find(l=>l.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey:s=n.find(l=>l.columnName===s)?.databaseName||s,G(t.table,s,r)}generateDestructiveOperations(t){return this.dropResolver.generateDropOperations(t)}generateColumnModificationOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.generateModifyColumnViaAlter(r);e.push({type:"MODIFY_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:r.table,column:r.dbColumns.name,data:r,dependencies:[],sqlStatements:o});}return e}getForeignKeyDependencies(t){let e=[];if(t.relation.type==="belongsTo"){let o=t.relation.model();e.push(`table.${o.table}`);let n=o.primaryKey||"id",s=o.getColumns().find(a=>a.columnName===n);s&&e.push(`column.${o.table}.${s.databaseName}`);}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let o=q(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s=e[r.type](...o);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||$e(t,r.columnName)}),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new Ie(this.sql.getDbType());return n.createIndex(t.table,o,{constraintName:t.index}),n.queryStatements[0]||""}generateAddRelationViaAlter(t){let e=t.table,r=t.relation.foreignKey;t.relation.type==="belongsTo"?(e=t.relation.model().table,r=t.relation.model().primaryKey||"id"):t.relation.type==="manyToMany"&&t.relation.manyToManyOptions&&(e=q(t.relation.manyToManyOptions.throughModel),r=q(t.relation.manyToManyOptions.rightForeignKey),(!r||r==="undefined")&&(r=t.relation.model().primaryKey||"id"));let o=typeof t.relation.constraintName=="string"?t.relation.constraintName:void 0,n=q(r);if(t.relation.type==="belongsTo"){let m=t.relation.model(),p=m.primaryKey,h=m.getColumns().find(T=>T.columnName===p);if(h)n=h.databaseName;else {let T=m?.databaseCaseConvention||"preserve";n=U(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.model();if(typeof n=="string"&&n){let p=m.getColumns(),y=p.find(h=>h.columnName===n);if(y)n=y.databaseName;else {let h=m.primaryKey||"id",T=p.find(S=>S.columnName===h);if(T)n=T.databaseName;else {let S=m?.databaseCaseConvention||"preserve";n=U(n||h,S);}}}else {let p=m.primaryKey||"id",h=m.getColumns().find(T=>T.columnName===p);if(h)n=h.databaseName;else {let T=m?.databaseCaseConvention||"preserve";n=U(p,T);}}}let s=this.models.find(m=>m.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(m=>m.columnName===l);if(d)l=d.databaseName;else {let m=s?.databaseCaseConvention||"preserve";l=U(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=U(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let m=t.relation.manyToManyOptions.leftForeignKey,p=q(m),y=a.find(h=>h.columnName===p);if(y)l=y.databaseName;else {let h=s?.databaseCaseConvention||"preserve";l=U(p,h);}}let u=t.relation.onDelete?.toLowerCase(),c=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,m=>{let p=o||G(t.table,l,e);m.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:u,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," "))}))}};function jf(i){return i.replace(/\s+/g," ").trim()}function Vf(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function De(i,t){let e=jf(t.toLowerCase()),r=Vf(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{if(r.endsWith("text")||r==="text")return "text";switch(r){case "int":case "integer":case "increment":return "integer";case "tinyint":return "boolean";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "uuid":return "varchar";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "timestamp":return "timestamp";case "time":return "time";case "year":return "year";case "jsonb":return "json";case "json":return "json";case "enum":return "enum";case "binary":return "binary";case "varbinary":return "varbinary";case "tinyblob":return "tinyblob";case "mediumblob":return "mediumblob";case "longblob":return "longblob";case "blob":return "blob";case "boolean":case "bool":return "boolean";default:return r}}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var Fe=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:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(u=>u?.type!==void 0&&u?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let c of n.indexes)o.indexes.map(m=>m.name).includes(c.name)||e.data.indexesToAdd.push({table:r.table,index:c.name});let u=r.getUniques?.()||[];for(let c of u)e.data.uniquesToAdd.push({table:r.table,name:c.name||"mandatory",columns:c.columns});for(let c of n.relations){if(c.type!=="belongsTo")continue;let m=q(c.constraintName);o.foreignKeys.find(y=>y.name===m)||e.data.relationsToAdd.push({table:r.table,relation:c,onDelete:c.onDelete,onUpdate:c.onUpdate});}return}for(let u of n.columns)o.columns.some(m=>m.name===u.databaseName||m.name===u.columnName)||e.data.columnsToAdd.push({table:r.table,column:u});for(let u of o.columns)n.columns.some(m=>m.databaseName===u.name||m.columnName===u.name)||e.data.columnsToDrop.push({table:r.table,column:u.name});for(let u of n.indexes)o.indexes.map(c=>c.name).includes(u.name)||e.data.indexesToAdd.push({table:r.table,index:u.name});let s=r.getUniques?.()||[];for(let u of s)o.indexes.some(m=>m.name===u.name&&m.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:u.name||"mandatory",columns:u.columns});let a=o.foreignKeys.map(u=>u.name);for(let u of o.indexes)u.isUnique||a.includes(u.name)||n.indexes.map(m=>m.name).includes(u.name)||e.data.indexesToDrop.push({table:r.table,index:u.name});for(let u of o.indexes){if(!u.isUnique||u.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(m=>m.name).includes(u.name)||e.data.uniquesToDrop.push({table:r.table,name:u.name});}for(let u of n.columns){let c=o.columns.find(y=>y.name===u.databaseName||y.name===u.columnName);if(!c)continue;let m=!e.areColumnsEqual(c,u,o.indexes),p=e.getDefaultChange({table:r.table,dbColumns:c,modelColumn:u});(m||p)&&e.data.columnsToModify.push({table:r.table,dbColumns:c,modelColumn:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;if(u.type==="manyToMany"&&u.manyToManyOptions){let p=q(u.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:p,relation:{type:"belongsTo",model:()=>r,columnName:q(u.manyToManyOptions.leftForeignKey),foreignKey:u.manyToManyOptions.leftForeignKey,constraintName:u.constraintName?q(u.constraintName):G(p,q(u.manyToManyOptions.leftForeignKey||Pe(r.table)),r.table),onDelete:u.onDelete,onUpdate:u.onUpdate},onDelete:u.onDelete,onUpdate:u.onUpdate});continue}let c=q(u.constraintName);if(c&&o.foreignKeys.some(p=>p.name===c))continue;o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,u,p))||e.data.relationsToAdd.push({table:r.table,relation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let l=new Set(n.relations.filter(u=>u.type==="belongsTo").map(u=>{let c=q(u.foreignKey)||u.columnName,p=r.getColumns().find(y=>y.columnName===c)?.databaseName||c;return q(u.constraintName)||G(r.table,p,u.model().table)}));for(let u of o.foreignKeys){if(u.name&&l.has(u.name))continue;n.relations.find(m=>m.type!=="belongsTo"&&m.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,m,u))||e.data.relationsToDrop.push({table:r.table,relation:u});}for(let u of n.relations){if(u.type!=="belongsTo"&&u.type!=="manyToMany")continue;let c=o.foreignKeys.find(m=>e.relationMatchesDbRelation(r,u,m));c&&!e.areRelationsEqual(c,u)&&e.data.relationsToModify.push({table:r.table,dbRelation:c,modelRelation:u,onDelete:u.onDelete,onUpdate:u.onUpdate});}let d=r.primaryKey;if(d&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[d]}),o.primaryKey&&!d&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),d&&o.primaryKey){let u=r.getColumns().find(c=>c.columnName===d);u&&!e.arePrimaryKeysEqual(o.primaryKey,u)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:d});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getSqlStatementsByPhase(){let t=new Sr(this.sql),e=t.generateOperations(this.data),r=t.formatSqlStatements(e),o={STRUCTURE_CREATION:[],CONSTRAINT_CREATION:[],DESTRUCTIVE_OPERATIONS:[]};for(let n of r)o[n.phase].push(...n.sqlStatements);return o}areColumnsEqual(t,e,r=[]){let o=t.name===e.databaseName,n=this.sql.getDbType(),s=De(n,t.dataType),a=typeof e.type=="string"?De(n,e.type):void 0;a&&o&&(o=s===a),e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let l=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&l||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,u=t.isNullable;o=o&&d===u;}return o}areRelationsEqual(t,e){let r=q(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),u=d.primaryKey||"id",c=d.getColumns().find(y=>y.columnName===u),m=d.table,p=c?.databaseName||u;o=o&&t.referencedTable===m&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=q(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===d;}let n=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&o&&(o=n===a),l&&o&&(o=s===l),o}relationMatchesDbRelation(t,e,r){let o,n=e;if(n&&n.model){if(typeof n.model=="function"&&n.model.table)o=n.model;else if(typeof n.model=="function")try{let h=n.model();h&&h.table&&(o=h);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?q(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=q(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),u=(n.type||"belongsTo")==="belongsTo"?q(n.foreignKey):n.columnName,c=l.find(h=>h.columnName===u);c&&(u=c.databaseName);let m=o.primaryKey||"id",y=o.getColumns().find(h=>h.columnName===m)?.databaseName||m;return r.columns.length===1&&r.columns[0]===u&&r.referencedColumns.length===1&&r.referencedColumns[0]===y}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=De(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?De(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",d=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&d?false:"drop";if(s&&a){let u=String(t.dbColumns.defaultValue),c=String(t.modelColumn.constraints?.default),m=this.normalizeDefaultValue(e,r,u),p=this.normalizeDefaultValue(e,o||r,c);return m!==p?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=q(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(D=>D.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",u=s.getColumns().find(D=>D.columnName===l),c=a.getColumns().find(D=>D.columnName===d);if(!u||!c)continue;let m=q(o.manyToManyOptions.leftForeignKey)||l,p=q(o.manyToManyOptions.rightForeignKey)||d,y=await this.sql.getTableSchema(n);if(!y.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(u,m),this.clonePkAsColumn(c,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:m,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let h=this.clonePkAsColumn(u,m),T=this.clonePkAsColumn(c,p),S=y.columns.find(D=>D.name===m),M=y.columns.find(D=>D.name===p),x=S?this.areColumnsEqual(S,h,y.indexes):false,_=M?this.areColumnsEqual(M,T,y.indexes):false;for(let D of y.foreignKeys){let Y=D.referencedTable===s.table,Z=D.referencedTable===a.table;if(!Y&&!Z)continue;let Te=Y?m:p,_e=D.columns[0];_e&&_e!==Te&&(this.data.relationsToDrop.push({table:n,relation:D}),_e!==m&&_e!==p&&this.data.columnsToDrop.push({table:n,column:_e}));}let P={};x||(P[h.databaseName]=h),_||(P[T.databaseName]=P[T.databaseName]||T);for(let D of Object.keys(P))this.data.columnsToAdd.push({table:n,column:P[D]});let O=this.buildBelongsToRelation(n,()=>s,m,l,void 0,o.onDelete,o.onUpdate),R=this.buildBelongsToRelation(n,o.model,p,d,void 0,o.onDelete,o.onUpdate),Q=y.foreignKeys.find(D=>D.referencedTable===s.table&&D.columns.length===1&&D.columns[0]===m),ke=y.foreignKeys.find(D=>D.referencedTable===a.table&&D.columns.length===1&&D.columns[0]===p);if(!Q){let D=y.foreignKeys.find(Y=>Y.referencedTable===s.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(O);}if(!ke){let D=y.foreignKeys.find(Y=>Y.referencedTable===a.table);D&&this.data.relationsToDrop.push({table:n,relation:D}),this.data.relationsToAdd.push(R);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,u=o.getColumns().find(m=>m.columnName===l)?.databaseName||l,c=q(a.constraintName)||G(o.table,u,a.model().table);s.add(c);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(h=>h.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let d=o.table,u=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let h=o.relation.model();d=h.table;let T=h.primaryKey||"id";u=h.getColumns().find(M=>M.columnName===T)?.databaseName||T;}let c=new Set([l,o.relation.columnName].filter(Boolean)),m=n.foreignKeys.some(h=>{if(h.columns.length!==1||h.referencedColumns.length!==1)return false;let T=c.has(h.columns[0]),S=h.referencedTable===d,M=h.referencedColumns[0]===u;return T&&S&&M}),p=q(o.relation.constraintName)||G(o.table,l,d),y=e.get(o.table)||new Set;if(m||p&&y.has(p))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let h=q(o.relation.manyToManyOptions.throughModel),T=q(o.relation.manyToManyOptions.leftForeignKey),S=q(o.relation.manyToManyOptions.rightForeignKey),M=o.table===h&&o.relation.columnName===T&&o.relation.model().table===s?.table,x=o.table===h&&o.relation.columnName===S&&o.relation.model().table!==s?.table,_=await this.sql.getTableSchema(h),P=_.foreignKeys.some(R=>R.columns.length===1&&R.columns[0]===T&&R.referencedTable===(s?.table||"")),O=_.foreignKeys.some(R=>R.columns.length===1&&R.columns[0]===S&&R.referencedTable===o.relation.model().table);if(M&&P||x&&O)return null}return o})).then(o=>o.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async o=>{let n=this.models.find(d=>d.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(d=>{if(d.type!=="belongsTo")return false;let c=a.find(T=>T.columnName===d.foreignKey)?.databaseName||d.foreignKey,m=d.model(),p=m.primaryKey||"id",h=m.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===c&&o.relation.referencedTable===m.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===h})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?q(n):G(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 at=class extends w{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var K=class extends w{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var H=class extends w{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var ue=class extends w{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Se=class extends w{constructor(e,r=[],o=[],n=false){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o;}};var C=class extends w{constructor(e,r,o=false,n,s,a=false){super("where",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where";this.column=e,this.chainsWith=` ${r}`,this.isNegated=o,this.operator=n,this.value=s;}};var Ee=class extends w{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var oe=class extends C{constructor(e,r,o=false,n,s,a=false){super(e,r,o,"=",s,a);this.file="where_json";this.jsonOperator=n,this.value=s;}};var qe=class extends w{constructor(e,r,o,n="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_subquery";this.column=e,this.operator=r,this.subquery=o,this.chainsWith=` ${n}`;}};var Jf=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,Hf=/^\d{4}-\d{2}-\d{2}$/,Ua=i=>typeof i!="string"?i:Jf.test(i)?new Date(i.replace(" ","T")+"Z"):Hf.test(i)?new Date(i+"T00:00:00Z"):i,Yf=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),gp=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await Yf(r):t[e]=r;}return t};var qr=class extends Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:d=>{s=true,a=d;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(d=>{r=true,this.emit("error",d);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},bp=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((d,u)=>{n.run(i,t,function(c){c&&u(c),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,u)=>{n.all(i,t,(c,m)=>{c&&u(c),(!m||!m.length)&&d([]),d(m);});});let s=r?.typeofModel;if(!s)return new Promise((d,u)=>{n.run(i,t,function(c){c?u(new Error(c.message)):d(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((c,m)=>{n.run(i,t,function(p){if(p)return m(p);let y=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){c([y]);return}let h=y?.[a]||this.lastID;if(!h)return m(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[h],(S,M)=>{if(S)return m(S);c([M]);});});});if(!Array.isArray(r.models))throw new N("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models;if(!a)return new Promise((c,m)=>{n.run(i,t,function(p){if(p)return m(p);c(d);});});let u=[];return new Promise(async(c,m)=>{try{let p=d.map(async y=>{let h=new f(s),{columns:T,values:S}=await h.prepareColumns(Object.keys(y),Object.values(y),"insert"),M=Object.fromEntries(T.map((O,R)=>[O,S[R]])),x=new b(s,e.getDbType()),{sql:_,bindings:P}=x.parse([new H(new K(s.table),[M])]);return new Promise((O,R)=>{n.run(_,P,function(Q){if(Q)return R(Q);let ke=y[a]||this.lastID;if(!ke)return R(new N("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let D=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(D,[ke],(Y,Z)=>{if(Y)return R(Y);O(Z);});});})});u=await Promise.all(p),c(u);}catch(p){m(p);}})}return new Promise((d,u)=>{n.run(i,t,function(c){c?u(new Error(c.message)):d(this.changes);});})};var j=async(i,t,e,r,o="rows",n)=>{switch(n?.shouldNotLog||ee(i,e.logs,t),r){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool(),a=await Mt(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?a[0].affectedRows:o==="raw"?a:a[0];case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool(),d=0,u=i.replace(/\?/g,()=>`$${++d}`),c=await Mt(()=>l.query(u,t),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="rows"?c.rows:o==="raw"?c:c.rowCount;case "sqlite":let m=await Mt(()=>bp(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="raw"?Array.isArray(m)?m:[m]:m;case "mssql":let p=e.getPool(),y=e.sqlConnection?e.sqlConnection.request():p.request();t.forEach((P,O)=>{y.input(`p${O}`,P);});let h=0,T=i.replace(/\?|@(\d+)/g,()=>`@p${h++}`),S=await Mt(()=>y.query(T),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?S.rowsAffected[0]:o==="raw"?S:S.recordset;case "oracledb":let M=4002,x=null,_=!!e.sqlConnection;try{x=e.sqlConnection?e.sqlConnection:await e.getConnection();let P=t.map(Ua),O=0,R=i.replace(/\?/g,()=>`:${++O}`),Q=await Mt(()=>x.execute(R,P,{outFormat:M,autoCommit:!_}),e.inputDetails.connectionPolicies?.retry,e.logs);return o==="affectedRows"?Q.rowsAffected:o==="raw"?Q:await Promise.all(Q.rows?.map(async D=>{let Y=await gp(D),Z={};for(let Te in Y)Z[Te.toLowerCase()]=Y[Te];return Z})??[])}finally{x&&!_&&await x.close();}default:throw new N("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},_r=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),c=0,m=false,p=false,y=()=>{try{a.release();}catch{}};return u.on("data",h=>{if(o.onData){c++,Promise.resolve(o.onData(l,h)).then(()=>{c--,m&&c===0&&!p&&(y(),l.end());}).catch(T=>{p=true,y(),l.destroy(T);});return}l.write(h);}),u.on("end",()=>{m=true,c===0&&!p&&(y(),l.end());}),u.on("error",h=>{p=true,y(),l.destroy(h);}),l.on("close",()=>{y();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection??await s.connect(),l=await import('pg-query-stream').catch(()=>{throw new B("pg-query-stream")}),d=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),u=0,c=i.replace(/\?/g,()=>`$${++u}`),m=new l.default(c,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),p=a.query(m),y=0,h=false,T=false,S=M=>{try{a.release(M);}catch{}};return p.on("data",M=>{if(o.onData){y++,Promise.resolve(o.onData(d,M)).then(()=>{y--,h&&y===0&&!T&&(S(),d.end());}).catch(x=>{T=true,S(x),d.destroy(x);});return}d.write(M);}),p.on("end",()=>{h=true,y===0&&!T&&(S(),d.end());}),p.on("error",M=>{T=true,S(M),d.destroy(M);}),d}case "sqlite":{let s=e.sqlConnection??e.getPool();return new qr(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((y,h)=>{l.input(`p${h}`,y);});let d=0,u=i.replace(/\?|@(\d+)/g,()=>`@p${d++}`),c=0,m=false,p=false;return l.on("row",y=>{if(!p){if(o.onData){c++,Promise.resolve(o.onData(a,y)).then(()=>{c--,m&&c===0&&!p&&a.end();}).catch(h=>{p=true,a.destroy(h);});return}a.write(y);}}),l.on("error",y=>{p=true,a.destroy(y);}),l.on("done",()=>{m=true,c===0&&!p&&a.end();}),l.query(u),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=4002,u=0,c=i.replace(/\?/g,()=>`:${++u}`),m=t.map(Ua),p=a.queryStream(c,m,{outFormat:d}),y=0,h=false,T=false,S=async()=>{try{await a.close();}catch{}};return p.on("data",M=>{if(T)return;let x={};for(let _ in M)x[_.toLowerCase()]=M[_];if(o.onData){y++,Promise.resolve(o.onData(l,x)).then(()=>{y--,h&&y===0&&!T&&(S(),l.end());}).catch(_=>{T=true,S(),l.destroy(_);});return}l.write(x);}),p.on("end",()=>{h=true,y===0&&!T&&(S(),l.end());}),p.on("error",M=>{T=true,S(),l.destroy(M);}),l}default:throw new N("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function Mt(i,t={maxRetries:0,delay:0},e=false){let r=0,o=t.maxRetries||0,n=t.delay||0;async function s(){try{return i()}catch(a){if(!Object.prototype.hasOwnProperty.call(a,"code")||a.code!=="ECONNREFUSED")throw a;if(r<o)return r++,Ga(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var L=(i,t="millis",e=3)=>async(...r)=>{let o=performance.now(),n=await i(...r),s=performance.now()-o;return [(t==="millis"?s:s/1e3).toFixed(e),n]};var _t=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Ht(t),this.modelRelationsMap=new Map(this.modelRelations.map(o=>[o.columnName,o]));}getRelationFromModel(t){let e=this.modelRelationsMap.get(t.toString());if(!e)throw new N("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Cr(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function Tp(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var lt=i=>typeof i=="number"?i:parseFloat(i);var ie=class extends w{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var je=class extends w{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var Rr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var xr=class extends w{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var ve=class extends w{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var ne=class extends w{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var Ct=class extends w{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var Ar=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var Pr=class extends w{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var Rt=class extends w{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var $r=class{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs;let r=this.model?.getColumns;this.modelColumns=typeof r=="function"?r.call(this.model):[],this.modelColumnsMap=new Map(this.modelColumns.map(o=>[o.columnName,o]));}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new Ct(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Ct(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new Rt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new Rt(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 Ar(t),this}offset(t){return typeof t!="number"&&g.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new Pr(t),this}};var Ve=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new C(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new C(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new C(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 C(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new C(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 C(t,"and",false,"in",e)),this):(this.whereNodes.push(new C("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new C(t,"or",false,"in",e)),this):(this.whereNodes.push(new C("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new C(t,"and",true,"in",e)),this):(this.whereNodes.push(new C("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new C(t,"or",true,"in",e)),this):(this.whereNodes.push(new C("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new C(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new C(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new C(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new C(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 C(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 C(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 C(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 C(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 Ee(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 Ee(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new C(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new C(t,"or",true,"=",e??[],true)),this}};var Or=class extends $r{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ne(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ne(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ne(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ne(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ne(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ne(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,d)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,d)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,d)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new N("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let d;if(l){let u=new Ve(this.sqlDataSource);l(u),d=u.getConditions();}return this.joinNodes.push(new ne(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,d)),this}};var Ir=class extends Or{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new K(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=U(s,this.model.databaseCaseConvention);this.selectNodes.push(new ie(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=U(o,this.model.databaseCaseConvention);this.selectNodes.push(new ie(n));}),this}selectRaw(e){return this.selectNodes.push(new ie(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":U(r,this.model.databaseCaseConvention);return this.selectNodes.push(new ie(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new K(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}from(e){return this.fromNode=new K(e),this}table(e){return this.fromNode=new K(e),this}distinct(){return this.distinctNode=new Rr,this}distinctOn(...e){return this.distinctOnNode=new xr(e),this}selectJson(e,r,o){return this.selectNodes.push(new ve(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new ve(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new ve(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new ve(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new ve(e,"",r,"raw",true)),this}};var Dr=class extends Ir{constructor(e,r,o=false){super(e,r);this.isNestedCondition=false;this.whereNodes=[],this.havingNodes=[],this.isNestedCondition=o;}clearWhere(){return this.whereNodes=[],this}clearHaving(){return this.havingNodes=[],this}strictWhen(e,r){return e==null?this:(r(this),this)}when(e,r){return e?(r(this),this):this}where(e,r,o){return typeof e=="function"?this.andWhereGroup(e):typeof r=="function"&&o===void 0?this.andWhereSubQuery(e,"in",r):r instanceof k&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof k||typeof o=="function")?this.andWhereSubQuery(e,r,o):this.andWhere(e,r,o)}andWhere(e,r,o){if(typeof e=="function")return this.andWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(r instanceof k&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",false,n,s)),this}orWhere(e,r,o){if(typeof e=="function")return this.orWhereGroup(e);if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(r instanceof k&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"or",false,n,s)),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof k&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",true,n,s)),this}andWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof k&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"and",true,n,s)),this}orWhereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(r instanceof k&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof k||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof k)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new C(e,"or",true,n,s)),this}whereBetween(e,r,o){return this.andWhereBetween(e,r,o)}andWhereBetween(e,r,o){return this.whereNodes.push(new C(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new C(e,"or",false,"between",[r,o])),this}whereNotBetween(e,r,o){return this.andWhereNotBetween(e,r,o)}andWhereNotBetween(e,r,o){return this.whereNodes.push(new C(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new C(e,"or",true,"between",[r,o])),this}whereLike(e,r){return this.andWhereLike(e,r)}andWhereLike(e,r){return this.where(e,"like",r),this}orWhereLike(e,r){return this.orWhere(e,"like",r),this}whereILike(e,r){return this.andWhereILike(e,r)}andWhereILike(e,r){return this.where(e,"ilike",r),this}orWhereILike(e,r){return this.orWhere(e,"ilike",r),this}whereNotLike(e,r){return this.andWhereNotLike(e,r)}andWhereNotLike(e,r){return this.where(e,"not like",r),this}orWhereNotLike(e,r){return this.orWhere(e,"not like",r),this}whereNotILike(e,r){return this.andWhereNotILike(e,r)}andWhereNotILike(e,r){return this.where(e,"not ilike",r),this}orWhereNotILike(e,r){return this.orWhere(e,"not ilike",r),this}whereIn(e,r){return this.andWhereIn(e,r)}andWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"and",false,"in",r)),this):(this.whereNodes.push(new C("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"or",false,"in",r)),this):(this.whereNodes.push(new C("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 C(e,"and",true,"in",r)),this):(this.whereNodes.push(new C("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new C(e,"or",true,"in",r)),this):(this.whereNodes.push(new C("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new C(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new C(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new C(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new C(e,"or",false,"is not null",void 0)),this}whereRegexp(e,r){return this.andWhereRegexp(e,r)}andWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(e,"and",false,o?"~":"regexp",r.source)),this}orWhereRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new C(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new C(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof k?e:new k(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new qe("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new C(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new C(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new je(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new je(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new je(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new je(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof k)return e;let r=new k(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new qe(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new qe(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new k(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ee(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new k(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ee(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Er=class extends Dr{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new oe(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new oe(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new oe(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new oe(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new oe(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new oe(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new oe(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new oe(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new oe(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new oe(t,"or",false,"raw",e)),this}};var k=class i extends Er{constructor(e,r=Ae.instance){super(e,r);this.isNestedCondition=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),insert:this.insertWithPerformance.bind(this),insertMany:this.insertManyWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new b(this.model,this.dbType),this.interpreterUtils=new f(this.model);}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource);return r(n),this.selectNodes.push(new ie(n.extractQueryNodes(),o)),this}return this.selectNodes.push(new ie(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>j(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new N("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await _r(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let s=await this.many(),a=await n.getCount(),l=s[s.length-1],d=l?l[r.discriminator]:null;return [{paginationMetadata:Tp(e,a),data:s},{key:r.discriminator,value:d}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new qt("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new qt("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new We(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new We(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new We(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new We(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?lt(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&g.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:Cr(e,r,a),data:s}}from(e,r){if(typeof e=="function"){if(!r)throw new N("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new K(n,r),this}return this.fromNode=new K(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("normal",e,n)),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new N("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource);r(o);let n=o.extractQueryNodes();return this.withNodes.push(new it("materialized",e,n)),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new H(this.fromNode,[o],r,n),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((p,y)=>[p,a[y]]));this.insertNode=new H(this.fromNode,[l],r,n);let{sql:d,bindings:u}=this.astParser.parse([this.insertNode]),c=await this.getSqlDataSource("write"),m=await j(d,u,c,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(m)&&m.length?m[0]:m})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new H(this.fromNode,o,r,n),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async c=>{let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert");return Object.fromEntries(m.map((y,h)=>[y,p[h]]))}));this.insertNode=new H(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await this.getSqlDataSource("write"),u=await j(a,l,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return u})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new H(new K(this.model.table),[a],void 0,true),this.onDuplicateNode=new ue(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),u=Object.fromEntries(l.map((h,T)=>[h,d[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([u],s,n,o,[e]);let{sql:c,bindings:m}=this.astParser.parse([new H(new K(this.model.table),[u],void 0,true),new ue(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),y=await j(c,m,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(y)?y:[y]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new H(new K(this.model.table),s,void 0,true),this.onDuplicateNode=new ue(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async m=>{let{columns:p,values:y}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert"),h=Object.fromEntries(p.map((T,S)=>[T,y[S]]));a.push(h);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:d}=this.astParser.parse([new H(new K(this.model.table),a,void 0,true),new ue(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),u=await this.getSqlDataSource("write"),c=await j(l,d,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(c)?c:[c]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),d=Q=>this.interpreterUtils.formatStringColumn("mssql",Q),u=[],c=e.map(Q=>`select ${a.map(D=>(u.push(Q[D]),`@${u.length}`)).join(", ")}`),m=a.map(d).join(", "),p=c.join(" union all "),y=r.map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(" and "),h=o.filter(Q=>!r.includes(Q)).map(Q=>`target.${d(Q)} = source.${d(Q)}`).join(", "),T=a.map(d).join(", "),S=a.map(Q=>`source.${d(Q)}`).join(", "),M=n.returning&&n.returning.length?n.returning.map(Q=>`inserted.${d(Q)}`).join(", "):a.map(Q=>`inserted.${d(Q)}`).join(", "),_=(n.updateOnConflict??true)&&h?`when matched then update set ${h}`:"",P=`merge into ${l} as target using (${p}) as source (${m}) on ${y} ${_} when not matched then insert (${T}) values (${S}) output ${M};`,O=await this.getSqlDataSource("write"),R=await j(P,u,O,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(R)?R:[R]}update(e){let r=Object.keys(e),o=Object.values(e);return this.updateNode=new Se(this.fromNode,r,o),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new Se(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return j(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}truncate(){return this.truncateNode=new st(this.fromNode),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await j(e,r,o,this.dbType,"rows");})}delete(){return this.deleteNode=new at(this.fromNode),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),o=await this.getSqlDataSource("write");return j(e,r,o,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=et()}=e||{};return this.updateNode=new Se(this.fromNode,[r],[o]),new J(()=>this.unWrap(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Se(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),d=await this.getSqlDataSource("write");return j(a,l,d,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return Ze(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new ie("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=xe(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=V(this.modelSelectedColumns),e.distinctNode=V(this.distinctNode),e.distinctOnNode=V(this.distinctOnNode),e.selectNodes=V(this.selectNodes),e.withQuery=V(this.withQuery),e.joinNodes=V(this.joinNodes),e.whereNodes=V(this.whereNodes),e.groupByNodes=V(this.groupByNodes),e.havingNodes=V(this.havingNodes),e.orderByNodes=V(this.orderByNodes),e.lockQueryNodes=V(this.lockQueryNodes),e.unionNodes=V(this.unionNodes),e.withNodes=V(this.withNodes),e.fromNode=V(this.fromNode),e.limitNode=V(this.limitNode),e.offsetNode=V(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.from(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new ie("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}async manyWithPerformance(e="millis"){let[r,o]=await L(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await L(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await L(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await L(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await L(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await L(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await L(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};var dt=class i extends k{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),paginate:this.paginateWithPerformance.bind(this),exists:this.existsWithPerformance.bind(this),paginateWithCursor:this.paginateWithCursorWithPerformance.bind(this),truncate:this.truncateWithPerformance.bind(this),delete:this.deleteWithPerformance.bind(this),update:this.updateWithPerformance.bind(this),softDelete:this.softDeleteWithPerformance.bind(this),pluck:this.pluckWithPerformance.bind(this)};this.sqlModelManagerUtils=new _t(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=new Map,this.modelColumnsDatabaseNames=new Map,this.model.getColumns().forEach(n=>{this.modelColumnsMap.set(n.databaseName,n),this.modelColumnsDatabaseNames.set(n.databaseName,n.columnName);});}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){return r.connection?new i(e,r.connection):r.trx?new i(e,r.trx.sql):new i(e,e.sqlInstance)}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new N(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a,this.model));if(!o.length)return [];let n=await ye(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsRecursively(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await _r(r,o,n,e,{onData:async(a,l)=>{let d=this.addAdditionalColumnsToModel(l,this.model),u=await ye([d],this.model,this.modelSelectedColumns);u&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([u]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([u]),a.write(u));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new N(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(...e){return this.model.insert(...e)}insertMany(...e){return this.model.insertMany(...e)}upsert(...e){return this.model.upsert(...e)}upsertMany(...e){return this.model.upsertMany(...e)}update(e,r={}){let o=super.update(e);return new J(()=>o.unWrap(),()=>o.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),o))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new J(()=>r.unWrap(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=super.delete();return new J(()=>r.unWrap(),()=>r.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),r))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,d]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:Cr(e,r,d),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof k)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r){let o=this.sqlModelManagerUtils.getRelationFromModel(e),n=new i(o.model,this.sqlDataSource);return n.relation=o,r?.(n),this.relationQueryBuilders.push(n),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereExists(u),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereExists(u),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.whereNotExists(u),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),d=new i(l.model,this.sqlDataSource);d.relation=l;let u=this.getRelatedModelsQueryForRelation(d,l,[]);return u.clearWhere(),u.clearSelect(),u.selectRaw("1"),a?.(u),this.applyHavingRelatedFilter(u,l,s,n),this.orWhereNotExists(u),this}clone(){let e=super.clone();return e.relationQueryBuilders=V(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(m=>{let p=m[e.foreignKey];p&&n.set(String(p),m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=null;return}let y=n.get(String(p));m[e.columnName]=y||null;});break;case "belongsTo":let s=new Map;o.forEach(m=>{if(!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=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 y=s.get(String(p));m[e.columnName]=y||null;});break;case "hasMany":if(!this.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(m=>{let p=m[e.foreignKey];if(!p)return;let y=String(p);a.has(y)||a.set(y,[]),a.get(y).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let y=a.get(String(p))||[];m[e.columnName]=y;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new N(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,u=l.leftForeignKey,c=this.modelColumnsMap.get(u)||this.modelColumnsDatabaseNames.get(u)||U(u,this.model.modelCaseConvention);o.forEach(m=>{let p=m[c];if(p==null)return;let y=String(p);d.has(y)||d.set(y,[]),delete m[c],d.get(y).push(m);}),r.forEach(m=>{let p=m[this.model.primaryKey];if(!p){m[e.columnName]=[];return}let y=d.get(String(p))||[];m[e.columnName]=y;});break;default:throw new N(this.model.name+"::mapRelatedModelsToModels","UNSUPPORTED_RELATION_TYPE")}}async getRelatedModelsForRelation(e,r,o){return this.getRelatedModelsQueryForRelation(e,r,o).many()}getRelatedModelsQueryForRelation(e,r,o){let n=this.getFilterValuesFromModelsForRelation(r,o);switch(r.type){case "belongsTo":case "hasOne":return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);case "hasMany":let s=e.limitNode?.limit,a=e.offsetNode?.offset;if(!s&&!a)return e.whereIn(e.relation.type==="belongsTo"?r.model.primaryKey:r.foreignKey,n);let l=Ne.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,u=e.orderByNodes.map(R=>R.isRawValue?R.column:`${this.interpreterUtils.formatStringColumn(this.dbType,R.column)} ${R.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let c=e.with(d,R=>R.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${u}) as rn_${l}`).whereIn(r.foreignKey,n));s&&c.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&c.whereRaw(`rn_${l} > ${a}`);let m=e.modelSelectedColumns.map(R=>so(R,d,e.model.table));return c.select(...m).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new N(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let y=e.limitNode?.limit,h=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(R=>R.includes(".")?R:`${r.model.table}.${R}`):[`${r.model.table}.*`];if(!y&&!h)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let S=Ne.randomBytes(6).toString("hex"),M=`${r.model.table}_cte_${S}`,x=e.orderByNodes.map(R=>{if(R.isRawValue)return R.column;let Q=R.column.includes(".")?R.column:`${r.model.table}.${R.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,Q)} ${R.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let _=`${Ne.randomBytes(6).toString("hex")}_left_foreign_key`,P=e.with(M,R=>R.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,_]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${x}) as rn_${S}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));y&&P.whereRaw(`rn_${S} <= ${y+(h||0)}`),h&&P.whereRaw(`rn_${S} > ${h}`);let O=T.map(R=>so(R,M,e.model.table));return P.select(...O).select([`${M}.${_}`,p.leftForeignKey]).from(M);default:throw new N(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);case "belongsTo":return r.map(o=>o[e.foreignKey]);case "manyToMany":if(!this.model.primaryKey)throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new N(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new f(r.model),a=new f(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),u=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new N(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let d=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),u=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${u}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let d=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new N(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===d.throughModel&&p.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let c=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${c} = ${m}`),o&&typeof n=="number"&&e.groupByRaw(c).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new N(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={};return Object.entries(e).forEach(([n,s])=>{if(this.modelColumnsDatabaseNames.get(n)){o[n]=s;return}o[n]=s;}),o}async manyWithPerformance(e={},r="millis"){let[o,n]=await L(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await L(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await L(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await L(this.paginate.bind(this,e,r,{ignoreHooks:s}),n)();return {data:{paginationMetadata:l.paginationMetadata,data:l.data},time:Number(a)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await L(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await L(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await L(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await L(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await L(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await L(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await L(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var xt=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=wl(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new b(this.model,this.sqlType),this.interpreterUtils=new f(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new N(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new N(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(l=>[l,t[l]])),o=!e.returning||e.returning.length===0,n=new H(new K(this.model.table),[r],e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:xe(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return Ze(l,d)};return new J(s,a,async()=>{e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),u={};l.forEach((S,M)=>{let x=d[M];u[S]=x,t[S]??(t[S]=x);});let c=!e.returning||e.returning.length===0,{sql:m,bindings:p}=this.astParser.parse([new H(new K(this.model.table),[u],e.returning,c)]),y=await j(m,p,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let h=y[0];return h?(await this.model.afterFetch?.([h]),await ye([h],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(l=>Object.fromEntries(Object.keys(l).map(d=>[d,l[d]]))),o=!e.returning||e.returning.length===0,n=new H(new K(this.model.table),r,e.returning,o),s=()=>{let l=this.astParser.parse([n]);return {sql:xe(this.sqlDataSource,l.sql),bindings:l.bindings}},a=()=>{let{sql:l,bindings:d}=s();return Ze(l,d)};return new J(s,a,async()=>{if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let h=this.model.primaryKey,T=Object.keys(t[0]||{});if(h&&!T.includes(h))return this.handleOracleIdentityInsert(t,e)}let l=[];for(let h of t){let{columns:T,values:S}=await this.interpreterUtils.prepareColumns(Object.keys(h),Object.values(h),"insert"),M={};T.forEach((x,_)=>{let P=S[_];M[x]=P,h[x]??(h[x]=P);}),l.push(M);}let d=!e.returning||e.returning.length===0,{sql:u,bindings:c}=this.astParser.parse([new H(new K(this.model.table),l,e.returning,d)]),m=await j(u,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(m,t,"many",e.returning)||[];let p=m;return p.length?(await this.model.afterFetch?.(p),await ye(p,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(u=>Object.fromEntries(Object.keys(u).map(c=>[c,u[c]]))),s=new H(new K(this.model.table),n,void 0,true),a=new ue(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning),l=()=>{let u=this.astParser.parse([s,a]);return {sql:xe(this.sqlDataSource,u.sql),bindings:u.bindings}},d=()=>{let{sql:u,bindings:c}=l();return Ze(u,c)};return new J(l,d,async()=>{let u=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async y=>{let{columns:h,values:T}=await this.interpreterUtils.prepareColumns(Object.keys(y),Object.values(y),"insert"),S=Object.fromEntries(h.map((M,x)=>[M,T[x]]));u.push(S);})),this.sqlType==="mssql")return this.executeMssqlMerge(u,t,e,o,r);let{sql:c,bindings:m}=this.astParser.parse([new H(new K(this.model.table),u,void 0,true),new ue(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await j(c,m,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=O=>this.interpreterUtils.formatStringColumn("mssql",O),d=[],u=t.map(O=>`select ${s.map(Q=>(d.push(O[Q]),`@${d.length}`)).join(", ")}`),c=s.map(l).join(", "),m=u.join(" union all "),p=e.map(O=>`target.${l(O)} = source.${l(O)}`).join(" and "),y=r.filter(O=>!e.includes(O)).map(O=>`target.${l(O)} = source.${l(O)}`).join(", "),h=s.map(l).join(", "),T=s.map(O=>`source.${l(O)}`).join(", "),S=o.returning&&o.returning.length?o.returning.map(O=>`inserted.${l(O)}`).join(", "):s.map(O=>`inserted.${l(O)}`).join(", "),x=(o.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",_=`merge into ${a} as target using (${m}) as source (${c}) on ${p} ${x} when not matched then insert (${h}) values (${T}) output ${S};`;return await j(_,d,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}})}async updateRecord(t,e){let r=new Set(this.model.getColumns().map(p=>p.columnName)),o=Object.keys(t).filter(p=>r.has(p)),n=o.map(p=>t[p]),{columns:s,values:a}=await this.interpreterUtils.prepareColumns(o,n,"update"),{primaryKey:l}=this.model;if(!l)throw new N(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=s.indexOf(l);d!==-1&&(s.splice(d,1),a.splice(d,1));let{sql:u,bindings:c}=this.astParser.parse([new Se(new K(this.model.table),s,a),new C(l,"and",false,"=",t[l])]);await j(u,c,this.sqlDataSource,this.sqlType,"affectedRows");let m=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!m)throw new N(this.model.name+"::updateRecord","ROW_NOT_FOUND");return m}async deleteRecord(t){if(!this.model.primaryKey)throw new N(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new C(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new at(new K(this.model.table)),e]);await j(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new dt(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await ye([a],this.model):null}return await ye(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(u=>u[this.model.primaryKey]),l=a.map(u=>`'${u}'`).join(","),d=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?d.length?d[0]:null:d}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,y)=>{let h=a[y];l[p]=h,n[p]??(n[p]=h);});let{sql:d,bindings:u}=this.astParser.parse([new H(new K(this.model.table),[l],e.returning)]);await j(d,u,this.sqlDataSource,this.sqlType,"rows");let c=this.query().select(...e.returning||["*"]);for(let[p,y]of Object.entries(l))y!=null&&p!==o&&c.where(p,"=",y);o&&c.orderBy(o,"desc");let m=await c.one({ignoreHooks:["beforeFetch"]});m?(o&&m[o]&&(n[o]=m[o]),r.push(m)):r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let d of n)this.handleWhereCondition(a,d,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,d]=a;o?t.orWhereBetween(e,l,d):t.whereBetween(e,l,d);break}case "$not between":{let[l,d]=a;o?t.orWhereNotBetween(e,l,d):t.whereNotBetween(e,l,d);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Np=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??et()});var At=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Ne.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await t(e);return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),ee("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;ee("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=!1;return}switch(this.sql.type){case "mssql":ee("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;ee("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":ee("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new N("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");g.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mssql":ee("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;ee("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":ee("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new N("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw g.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new N("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){g.error(t);}await this.sql.disconnect(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new N("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new N("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw g.error(e),new B("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new N("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var me,Me=class Me extends Ft{constructor(e){super(e);this.globalTransaction=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.cacheAdapter=new Ut;this.migrationConfig={path:I.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:zr(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new Me(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure;}getOnSlaveServerFailure(){return this.onSlaveServerFailure}static get instance(){if(!Qe(this,me))throw new N("SqlDataSource::instance","CONNECTION_NOT_ESTABLISHED");return Qe(this,me)}static async connectToSecondarySource(e,r){let o=new Me(e);await o.connectWithoutSettingPrimary();let n=o;return await r?.(n),n}static async useConnection(e,r){let o=new Me(e);await o.connectWithoutSettingPrimary();let n=o;try{await r(n),o.isConnected&&await o.disconnect();}catch(s){throw o.isConnected&&await o.disconnect(),s}}static async disconnect(){if(!Qe(this,me)){g.warn("Connection already closed");return}await Qe(this,me).disconnect(),Fr(this,me,null);}static async startGlobalTransaction(e){return this.instance.startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.instance.commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.instance.rollbackGlobalTransaction();}static get isInGlobalTransaction(){return !!Qe(this,me)?.globalTransaction}async connect(){if(Qe(Me,me))throw new N("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");this.sqlPool=await Be(this.sqlType,this.inputDetails),this.ownsPool=true,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await Be(e.sqlType,e.inputDetails),e.ownsPool=true;})),Fr(Me,me,this);}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){return this._models}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}async useCache(e,r,...o){if(!this.cacheAdapter)throw new N("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new N("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,d=[];a?(l=r,d=o):(l=void 0,d=r!==void 0?[r,...o]:o);let u=Gr(JSON.stringify(d)),c=u?`${e}:${u}`:e,m=await this.cacheAdapter.get(c);if(m!==void 0)return m;let p=await n(...d);return await this.cacheAdapter.set(c,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new N("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Gr(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new N("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new Me(this.inputDetails);return r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await Be(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new k(Np(e,r),o);return r?.alias&&n.from(e,r.alias),n}from(e){return new dt(e,this)}schema(){if(!this.isConnected)throw new N("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Tr(this,this.getDbType())}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new At(r,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new N("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){g.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=await this.clone();n.sqlConnection=await n.getConnection();let s=new At(n,o?.isolationLevel);if(await s.transaction(),typeof e=="function")try{let a=await e(s);return await s.commit({throwErrorOnInactiveTransaction:!1}),a}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}getModelManager(e){if(!this.isConnected)throw new N("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new xt(e,this.globalTransaction.sql):new xt(e,this)}getPool(){if(!this.sqlPool)throw new N("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new N("SqlDataSource::getConnection","CONNECTION_NOT_ESTABLISHED");switch(this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new N("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){ee("Connection already closed or not established",this.logs);return}if(!this.ownsPool){this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{g.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){g.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),ee("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new N("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){g.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await Fe.makeDiff(this)).getSqlStatements();if(!o.length){g.info("No new changes detected between database schema and models metadata");return}if(g.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);g.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),g.info(`Synced schema with ${o.length} SQL statements`);}extractRowsFromRawResult(e){let r=this.getDbType();if(r==="mysql"||r==="mariadb"){if(Array.isArray(e)&&e.length>=1){let o=e[0];if(Array.isArray(o))return o;if(typeof o=="object"&&o!==null&&("insertId"in o||"affectedRows"in o))return []}return e}return r==="postgres"||r==="cockroachdb"?e&&typeof e=="object"&&"rows"in e?e.rows||[]:e:Array.isArray(e)?e:[]}async rawQuery(e,r=[],o){if(!this.isConnected)throw new N("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let n=xe(this,e);return (o?.replicationMode||"master")==="slave"?this.executeOnSlave(async a=>j(n,r,a,this.getDbType(),"raw")):j(n,r,this,this.getDbType(),"raw")}rawStatement(e){return new $(e)}async getTableSchema(e){let[r,o,n,s]=await Promise.all([this.getTableInfo(e),this.getIndexInfo(e),this.getForeignKeyInfo(e),this.getPrimaryKeyInfo(e)]);return {columns:r,indexes:o,foreignKeys:n,primaryKey:s}}getModelOpenApiSchema(){return al(Object.values(this._models))}async initializeAdminJs(){if(!this.adminJsOptions?.enabled)throw new N("SqlDataSource::initializeAdminJs","ADMINJS_NOT_ENABLED");return this.adminJsInstance?this.adminJsInstance.admin:(this.adminJsInstance=await Yr(this,this.adminJsOptions),this.adminJsInstance?.admin)}async initializeAdminJsExpress(){if(!this.adminJsOptions?.enabled)throw new N("SqlDataSource::initializeAdminJsExpress","ADMINJS_NOT_ENABLED");return this.adminJsInstance?.router?this.adminJsInstance:(this.adminJsInstance=await il(this,this.adminJsOptions),this.adminJsInstance)}getAdminJs(){return this.adminJsInstance}getAdminJsOptions(){return this.adminJsOptions}isAdminJsEnabled(){return !!this.adminJsOptions?.enabled}async getTableInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new or(e)]).sql,n=[];try{let a=await this.rawQuery(o);n=this.extractRowsFromRawResult(a);}catch(a){if(Tt(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=De(s,l);return {name:a.name,dataType:d,isNullable:a.notnull===0,defaultValue:a.dflt_value??null,withTimezone:null}}):n.map(a=>{let l=String(a.column_name||a.COLUMN_NAME||a.name||""),d=String(a.data_type||a.DATA_TYPE||a.type||"").toLowerCase(),u=De(s,d),c=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,m=typeof c=="string"?c.toLowerCase()!=="no":typeof c=="boolean"?c:a.notnull!==void 0?a.notnull===0:true,p=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,y=a.char_length!=null?Number(a.char_length):null,h=a.numeric_precision!=null?Number(a.numeric_precision):null,T=a.numeric_scale!=null?Number(a.numeric_scale):null,S=a.timezone!=null?!!a.timezone:/with time zone/.test(String(a.column_type||a.udt_name||d||"").toLowerCase());return {name:l,dataType:u,isNullable:m,defaultValue:p,length:y,precision:h,scale:T,withTimezone:S}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new tr(e)]).sql,n=this.getDbType(),s=[];try{let l=await this.rawQuery(o);s=this.extractRowsFromRawResult(l);}catch(l){if(Tt(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let u=d.Key_name,c=d.Non_unique===0,m=l.get(u)||{name:u,columns:[],isUnique:c};m.columns.push(d.Column_name),l.set(u,m);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let u=d.index_name,c=!!d.is_unique,m=l.get(u)||{name:u,columns:[],isUnique:c};m.columns.push(d.column_name),l.set(u,m);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,u=!!l.unique,c=await this.rawQuery(`PRAGMA index_info(${d})`),p=this.extractRowsFromRawResult(c).map(y=>y.name);a.push({name:d,columns:p,isUnique:u});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new er(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Tt(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let u=Number(d.id),c=l.get(u)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};c.columns.push(String(d.from)),c.referencedColumns.push(String(d.to)),l.set(u,c);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),u=d||`${l.referenced_table}_${l.column_name}`,c=a.get(u)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};c.columns.push(String(l.column_name)),c.referencedColumns.push(String(l.referenced_column)),a.set(u,c);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new rr(e)]).sql,n=[];try{let l=await this.rawQuery(o);n=this.extractRowsFromRawResult(l);}catch(l){if(Tt(this.getDbType(),l))return;throw l}if(!n.length)return;let s=n.map(l=>String(l.column_name));return {name:n[0].name||void 0,columns:s}}async acquireLock(e="hysteria_lock",r=3e4){let o=this.getDbType();try{switch(o){case "postgres":case "cockroachdb":{let n=this.hashStringToLockId(e),a=(await this.rawQuery("SELECT pg_try_advisory_lock($1) as pg_try_advisory_lock",[n])).rows?.[0]?.pg_try_advisory_lock;return a===!0||a==="t"}case "mysql":case "mariadb":{let n=Math.floor(r/1e3);return (await this.rawQuery("SELECT GET_LOCK(?, ?) as lock_result",[e,n]))[0]?.[0]?.lock_result===1}case "mssql":return ((await this.rawQuery("DECLARE @result INT; EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = @p1; SELECT @result as lock_result",[e,r])).recordset?.[0]?.lock_result??-999)>=0;case "oracledb":try{let n=this.hashStringToLockId(e);return await this.rawQuery(`BEGIN DBMS_LOCK.ALLOCATE_UNIQUE('${e}', '${n}'); END;`),(await this.rawQuery(`DECLARE
|
|
290
290
|
v_result NUMBER;
|
|
291
291
|
BEGIN
|
|
292
292
|
v_result := DBMS_LOCK.REQUEST(
|