hysteria-orm 10.1.1 → 10.1.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.cjs +1 -1
- package/lib/cli.cjs.map +1 -1
- 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 +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -80,7 +80,7 @@ ORDER BY ordinal_position`,bindings:[]}}},la=new on;var nn=class{toSql(t){let e=
|
|
|
80
80
|
name as column_name
|
|
81
81
|
FROM pragma_table_info('${t.table}')
|
|
82
82
|
WHERE pk > 0
|
|
83
|
-
ORDER BY pk`,bindings:[]}}},el=new Jn;var Gn=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},tl=new Gn;var Zn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new 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}"`:""}},rl=new Zn;var Xn=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:[]}}},ol=new Xn;var es=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}}},nl=new es;var ts=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 de?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},sl=new ts;var rs=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}},il=new rs;var os=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}}},al=new os;var ns=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}}},ll=new ns;var ss=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}}},dl=new ss;var is=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}}},ul=new is;var cl={mysql:{alter_table:{add_column:As,add_constraint:xs,add_primary_key:Is,alter_column_type:Ps,alter_table:Es,drop_column:Bs,drop_constraint:$s,drop_default:vs,drop_not_null:Ks,drop_primary_key:Qs,rename_column:ks,rename_table:Fs,set_default:Ls,set_not_null:js},column:{column_type:Ws},constraint:{after:Us,constraint:Vs},create_table:{create_table:Hs},delete:{delete:Ys},distinct:{distinct:zs,distinct_on:Js},drop_table:{drop_table:Gs},from:{from:Zs},group_by:{group_by:Xs},having:{having:ei},index_op:{create_index:ti,drop_index:ri},insert:{insert:oi},join:{join:ni},limit:{limit:si},lock:{lock:ii},offset:{offset:ai},on_duplicate:{on_duplicate:li},order_by:{order_by:di},raw:{raw:ui},schema:{foreign_key_info:ci,index_info:mi,primary_key_info:pi,table_info:yi},select:{select:fi},truncate:{truncate:hi},union:{union:gi},update:{update:Ti},where:{where:bi,where_group:wi,where_json:Si,where_subquery:Ni},with:{with:Mi}},postgres:{alter_table:{add_column:qi,add_constraint:Ci,add_primary_key:Ri,alter_column_type:_i,alter_table:Oi,drop_column:Di,drop_constraint:Ai,drop_default:xi,drop_not_null:Ii,drop_primary_key:Pi,rename_column:Ei,rename_table:Bi,set_default:$i,set_not_null:vi},column:{column_type:Ki},constraint:{after:Qi,constraint:ki},create_table:{create_table:Fi},delete:{delete:Li},distinct:{distinct:ji,distinct_on:Wi},drop_table:{drop_table:Ui},from:{from:Vi},group_by:{group_by:Hi},having:{having:Yi},index_op:{create_index:zi,drop_index:Ji},insert:{insert:Gi},join:{join:Zi},limit:{limit:Xi},lock:{lock:ea},offset:{offset:ta},on_duplicate:{on_duplicate:ra},order_by:{order_by:oa},raw:{raw:na},schema:{foreign_key_info:sa,index_info:ia,primary_key_info:aa,table_info:la},select:{select:da},truncate:{truncate:ua},union:{union:ca},update:{update:ma},where:{where:pa,where_group:ya,where_json:fa,where_subquery:ha},with:{with:ga}},sqlite:{alter_table:{add_column:Ta,add_constraint:ba,alter_column_type:wa,alter_table:Sa,drop_column:Na,drop_constraint:Ma,drop_default:qa,drop_not_null:Ca,drop_primary_key:Ra,rename_column:_a,rename_table:Oa,set_default:Da,set_not_null:Aa},column:{column_type:xa},constraint:{after:Ia,constraint:Pa},create_table:{create_table:Ea},delete:{delete:Ba},distinct:{distinct:$a,distinct_on:va},drop_table:{drop_table:Ka},from:{from:Qa},group_by:{group_by:ka},having:{having:Fa},index_op:{create_index:La,drop_index:ja},insert:{insert:Wa},join:{join:Ua},limit:{limit:Va},lock:{lock:Ha},offset:{offset:Ya},on_duplicate:{on_duplicate:za},order_by:{order_by:Ja},raw:{raw:Ga},schema:{foreign_key_info:Za,index_info:Xa,primary_key_info:el,table_info:tl},select:{select:rl},truncate:{truncate:ol},union:{union:nl},update:{update:sl},where:{where:il,where_group:al,where_json:ll,where_subquery:dl},with:{with:ul}}};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(p=>!!p&&p.folder==="distinctOn"),n=!o&&t.find(p=>!!p&&p.folder==="distinct"),s=t.filter(p=>p!==null&&p.folder!=="distinct"&&p.folder!=="distinctOn"),a=[],l=[],d=null;for(let p=0;p<s.length;p++){let c=s[p];c.currParamIndex=e+l.length;let y=cl[this.mapCommonDbType(this.dbType)][c.folder][c.file];if(!y)throw new Error(`Interpreter not found for ${this.dbType} ${c.keyword}`);y.model=this.model;let h=y.toSql(c);if(!h.sql||!h.sql.trim().length)continue;let g=s[p+1],_=!g||g.keyword!==c.keyword?"":g.chainsWith;if(c.folder==="lock"||c.folder==="on_duplicate"||c.folder==="schema"){a.push(`${h.sql}${_}`),l.push(...h.bindings),d=c.keyword;continue}if(d!==c.keyword||c.canKeywordBeSeenMultipleTimes){if(r)a.push(`${h.sql}${_}`);else {let B=c.keyword;if(c.folder==="with"){let H=p,X=false;for(;H<s.length&&s[H].keyword===c.keyword;){let W=s[H];if(W.folder==="with"&&W.clause==="recursive"){X=true;break}H++;}X&&(B=`${B} recursive`);}if(B==="select")if(o){let H=Array.isArray(o.columns)?o.columns.join(", "):"";a.push(`select distinct on (${H}) ${h.sql}${_}`);}else n?a.push(`select distinct ${h.sql}${_}`):a.push(`select ${h.sql}${_}`);else a.push(`${B} ${h.sql}${_}`);}d=c.keyword;}else a.push(`${h.sql}${_}`);l.push(...h.bindings);}return {sql:a.join(" "),bindings:l}}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}};var ht=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var gt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Tt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var bt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var wt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ue=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var ke=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var St=class extends T{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var Te=class extends T{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 Nt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var ce=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var ze=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Mt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var Fe=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var qt=class extends T{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Ct=class extends T{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var Je=class extends T{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Rt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var k=class extends T{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 _t=class extends T{constructor(e,r=[],o=[],n=false){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;}};var Ot=class extends T{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 Dt=class extends T{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 At=class extends T{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 me=class extends T{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var xt=Symbol("columns"),It=Symbol("primaryKey"),te=Symbol("relations"),Pt=Symbol("indexes"),Et=Symbol("uniques"),Ne=i=>`${dd.singular(i)}_id`,Bt=(i,t)=>`idx_${i}_${t}`,ee=(i,t)=>`uq_${i}_${t}`,F=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,Me=(i,t)=>`pk_${i}_${t}`;var D=class extends T{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.isRawValue=o.isRawValue??false;}};var Ge=class extends T{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 De=class extends T{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 Le=class extends T{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 qe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var $t=class extends T{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var vt=class extends qe{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=Me(this.tableName,w(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new k("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new k("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??F(this.tableName??"",w(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new k("foreign_key",{columns:[w(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new k("foreign_key",{columns:[w(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 k("not_null",{columns:[w(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new k("null",{columns:[w(this.columnNode.column)]})),this}default(t){let e;return t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new k("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new k("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??ee(this.tableName??"",w(this.columnNode.column))})),this):(this.namedConstraints.push(new k("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName||ee(this.tableName??"",w(this.columnNode.column))})),this)}after(t){return this.nodes.push(new $t(t)),this}handleSqliteAutoIncrement(t){return this.nodes.push(new k("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Ae=class extends qe{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}build(e){return this.nodes.push(e),new vt(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}char(e,r=1){let o=new D(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new D(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new D(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 D(e,"uuid");return this.build(r)}ulid(e){let r=new D(e,"ulid");return this.build(r)}integer(e,r=255){let o=new D(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new D(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new D(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new D(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new D(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new D(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new D(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new D(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new D(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new D(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 D(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new D(e,"time",{precision:r});return this.build(o)}year(e){let r=new D(e,"year");return this.build(r)}datetime(e,r){let o=new D(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}timestamp(e,r){let o=new D(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}boolean(e){let r=new D(e,"boolean");return this.build(r)}binary(e){let r=new D(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new D(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new D(e,"blob");return this.build(r)}tinyblob(e){let r=new D(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new D(e,"mediumblob");return this.build(r)}longblob(e){let r=new D(e,"longblob");return this.build(r)}json(e){let r=new D(e,"json");return this.build(r)}jsonb(e){let r=new D(e,"jsonb");return this.build(r)}enum(e,r){let o=new D(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new D(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new D(e,"",{isRawValue:true});return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Kt=class extends qe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}addColumn(t){let e=[],r=new Ae(this.sqlType,e,this.table),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(p=>p.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(p=>{let c=p;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),d=new wt(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(p=>{let c=p;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(p=>{this.nodes.push(new ue(p));});}alterColumn(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Ae(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(c=>c.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=w(s.column),l=o.getNodes().find(c=>c.constraintType==="null"),m=o.getNodes().find(c=>c.constraintType==="not_null")||l,p=o.getNodes().find(c=>c.constraintType==="default");this.nodes.push(new St(w(a),s,{})),m&&(m.constraintType==="not_null"?this.nodes.push(new Rt(w(a))):m.constraintType==="null"&&this.nodes.push(new Mt(w(a)))),p&&(p.defaultValue===void 0||p.defaultValue===null?this.nodes.push(new ze(w(a))):this.nodes.push(new Je(w(a),p.defaultValue))),o.getNodes().forEach(c=>{let y=c;switch(y.constraintType){case "primary_key":this.addPrimaryKey(w(a));break;case "unique":this.unique(w(a),{constraintName:y.constraintName});break;case "foreign_key":this.addForeignKey(w(a),y.references?.table??"",w(y.references?.columns?.[0]??""),{constraintName:y.constraintName,onDelete:y.onDelete,onUpdate:y.onUpdate});break}});}dropColumn(t){this.nodes.push(new Nt(t));}renameColumn(t,e){this.nodes.push(new qt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ze(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ke([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ue(new k(...t)));}addForeignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ue(new k("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??F(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ue(new k("unique",{columns:[t],constraintName:e?.constraintName??ee(this.table,t)})));}setDefault(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Je(t,e));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=F(this.table,t,e);this.nodes.push(new ce(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new u("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??ee(this.table,t);this.nodes.push(new ce(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new u("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new Fe(t));}};var re=class{constructor(t){if(this.sqlType=t||M.DB_TYPE,!this.sqlType)throw new u("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawQuery(t){this.queryStatements.push(t);}runFile(t){if(!ml.existsSync(t))throw new u("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=ut.basename(t),r=ut.extname(e);if(r!==".sql"&&r!==".txt")throw new u("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=ml.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 Ae(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a=new _t(t,n,o.getNamedConstraints(),r?.ifNotExists),l=s.parse([a]).sql,d=l.startsWith("create table")?l:`create table ${l}`;this.rawQuery(d);}alterTable(t,e){let r=[],o=new Kt(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 l=new Te(t,s),d=n.parse([l]).sql;if(!d||!d.trim())return;let m=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(m),s=[];};for(let l of r)l.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(l);a();}dropTable(t,e=false){let r=new Ot(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new Te(t,[new Ct(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new me(t),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||Bt(t,e.join("_")),n=new Dt(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new At(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new ke(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??ee(t,o.join("_")),s=new k("unique",{columns:o,constraintName:n}),a=new Te(t,[new ue(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=F(t,e,r),n=new ce(o),s=new Te(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?ee(t,e.join("_")):ee(t,e),n=r?.constraintName??o,s=new ce(n),a=new Te(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new Fe,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new k(...e),o=new Te(t,[new ue(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new ce(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAstInstance(t){return new b(t,this.sqlType)}};var Qt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels);}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 m of d)m.type==="belongsTo"&&m.model().table===n.table&&a.push(`fk.${l.table}.${m.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(m=>m.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let m=l.getRelations();for(let p of m)p.columnName===d.columnName&&a.push(`fk.${n.table}.${p.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let 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(m=>m.table===a&&m.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){return this.sql.getDbType()==="sqlite"?[]:t.relation.name?this.sql.alterTable(t.table,e=>{e.dropConstraint(t.relation.name);}):[]}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,e=>{e.dropPrimaryKey();})}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);})}generateDropColumnSql(t){return this.sql.alterTable(t.table,e=>{e.dropColumn(t.column);})}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var kt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels),this.dropResolver=new Qt(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.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);}});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.alterTable(o.table,s=>{s.dropConstraint(o.name);});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 re(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||Me(o.table,o.columns[0]),l=this.sql.alterTable(o.table,d=>{let m=a||Me(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:m});});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(m=>m.columnName===l)?.databaseName||l),a=this.sql.alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});});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=w(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=w(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,F(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=w(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||Me(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.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});})}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.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.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});})}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 re(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=w(t.relation.manyToManyOptions.throughModel),r=w(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=w(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),y=c.primaryKey,g=c.getColumns().find(S=>S.columnName===y);if(g)n=g.databaseName;else {let S=c?.databaseCaseConvention||"preserve";n=I(y,S);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let y=c.getColumns(),h=y.find(g=>g.columnName===n);if(h)n=h.databaseName;else {let g=c.primaryKey||"id",S=y.find(_=>_.columnName===g);if(S)n=S.databaseName;else {let _=c?.databaseCaseConvention||"preserve";n=I(n||g,_);}}}else {let y=c.primaryKey||"id",g=c.getColumns().find(S=>S.columnName===y);if(g)n=g.databaseName;else {let S=c?.databaseCaseConvention||"preserve";n=I(y,S);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(c=>c.columnName===l);if(d)l=d.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=I(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(y=>y.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let y=s?.databaseCaseConvention||"preserve";l=I(t.relation.foreignKey,y);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,y=w(c),h=a.find(g=>g.columnName===y);if(h)l=h.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=I(y,g);}}let m=t.relation.onDelete?.toLowerCase(),p=t.relation.onUpdate?.toLowerCase();return this.sql.alterTable(t.table,c=>{let y=o||F(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:y,onDelete:m,onUpdate:p});})}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 md(i){return i.replace(/\s+/g," ").trim()}function pd(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ce(i,t){let e=md(t.toLowerCase()),r=pd(e);switch(i){case "sqlite":{let o=[{test:n=>n.includes("int"),normalized:"integer"},{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":return "integer";case "tinyint":return "tinyint";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";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 "character varying":return "varchar";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":return "integer";case "mediumint":return "integer";case "bigint":case "int8":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}}default:return r}}var Ft=class i{constructor(t){this.emptyStatements=[/alter table ".*"$/];this.sql=t,this.models=Object.values(this.sql.registeredModels),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(d=>d?.type!==void 0&&d?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let m of n.indexes)o.indexes.map(p=>p.name).includes(m.name)||e.data.indexesToAdd.push({table:r.table,index:m.name});let d=r.getUniques?.()||[];for(let m of d)e.data.uniquesToAdd.push({table:r.table,name:m.name||"mandatory",columns:m.columns});for(let m of n.relations){if(m.type!=="belongsTo")continue;let p=w(m.constraintName);o.foreignKeys.find(y=>y.name===p)||e.data.relationsToAdd.push({table:r.table,relation:m,onDelete:m.onDelete,onUpdate:m.onUpdate});}return}for(let d of n.columns)o.columns.some(p=>p.name===d.databaseName||p.name===d.columnName)||e.data.columnsToAdd.push({table:r.table,column:d});for(let d of o.columns)n.columns.some(p=>p.databaseName===d.name||p.columnName===d.name)||e.data.columnsToDrop.push({table:r.table,column:d.name});for(let d of n.indexes)o.indexes.map(m=>m.name).includes(d.name)||e.data.indexesToAdd.push({table:r.table,index:d.name});let s=r.getUniques?.()||[];for(let d of s)o.indexes.some(p=>p.name===d.name&&p.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:d.name||"mandatory",columns:d.columns});for(let d of o.indexes)d.isUnique||n.indexes.map(p=>p.name).includes(d.name)||e.data.indexesToDrop.push({table:r.table,index:d.name});for(let d of o.indexes){if(!d.isUnique)continue;(r.getUniques?.()||[]).map(p=>p.name).includes(d.name)||e.data.uniquesToDrop.push({table:r.table,name:d.name});}for(let d of n.columns){let m=o.columns.find(y=>y.name===d.databaseName||y.name===d.columnName);if(!m)continue;let p=!e.areColumnsEqual(m,d,o.indexes),c=e.getDefaultChange({table:r.table,dbColumns:m,modelColumn:d});(p||c)&&e.data.columnsToModify.push({table:r.table,dbColumns:m,modelColumn:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;if(d.type==="manyToMany"&&d.manyToManyOptions){let c=w(d.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:c,relation:{type:"belongsTo",model:()=>r,columnName:w(d.manyToManyOptions.leftForeignKey),foreignKey:d.manyToManyOptions.leftForeignKey,constraintName:d.constraintName?w(d.constraintName):F(c,w(d.manyToManyOptions.leftForeignKey||Ne(r.table)),r.table),onDelete:d.onDelete,onUpdate:d.onUpdate},onDelete:d.onDelete,onUpdate:d.onUpdate});continue}let m=w(d.constraintName);if(m&&o.foreignKeys.some(c=>c.name===m))continue;o.foreignKeys.find(c=>e.relationMatchesDbRelation(r,d,c))||e.data.relationsToAdd.push({table:r.table,relation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let a=new Set(n.relations.filter(d=>d.type==="belongsTo").map(d=>{let m=w(d.foreignKey)||d.columnName,c=r.getColumns().find(y=>y.columnName===m)?.databaseName||m;return w(d.constraintName)||F(r.table,c,d.model().table)}));for(let d of o.foreignKeys){if(d.name&&a.has(d.name))continue;n.relations.find(p=>p.type!=="belongsTo"&&p.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,p,d))||e.data.relationsToDrop.push({table:r.table,relation:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;let m=o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,d,p));m&&!e.areRelationsEqual(m,d)&&e.data.relationsToModify.push({table:r.table,dbRelation:m,modelRelation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let l=r.primaryKey;if(l&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[l]}),o.primaryKey&&!l&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),l&&o.primaryKey){let d=r.getColumns().find(m=>m.columnName===l);d&&!e.arePrimaryKeysEqual(o.primaryKey,d)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:l});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat()}getSqlStatementsByPhase(){let t=new kt(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=Ce(n,t.dataType),a=typeof e.type=="string"?Ce(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")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,m=t.isNullable;o=o&&d===m;}return o}areRelationsEqual(t,e){let r=w(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),m=d.primaryKey||"id",p=d.getColumns().find(h=>h.columnName===m),c=d.table,y=p?.databaseName||m;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===y;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=w(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 g=n.model();g&&g.table&&(o=g);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?w(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=w(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),m=(n.type||"belongsTo")==="belongsTo"?w(n.foreignKey):n.columnName,p=l.find(g=>g.columnName===m);p&&(m=p.databaseName);let c=o.primaryKey||"id",h=o.getColumns().find(g=>g.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===m&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&n}getDefaultChange(t){let e=this.sql.getDbType(),r=Ce(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Ce(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||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 n=t.modelColumn.constraints?.default!==void 0,s=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0;if(n&&!s)return "set";if(!n&&s)return "drop";if(n&&s){let a=String(t.dbColumns.defaultValue),l=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,a),m=this.normalizeDefaultValue(e,o||r,l);return d!==m?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o)?"current_timestamp":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=w(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(x=>x.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",m=s.getColumns().find(x=>x.columnName===l),p=a.getColumns().find(x=>x.columnName===d);if(!m||!p)continue;let c=w(o.manyToManyOptions.leftForeignKey)||l,y=w(o.manyToManyOptions.rightForeignKey)||d,h=await this.sql.getTableSchema(n);if(!h.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(m,c),this.clonePkAsColumn(p,y)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:y,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(m,c),S=this.clonePkAsColumn(p,y),_=h.columns.find(x=>x.name===c),B=h.columns.find(x=>x.name===y),H=_?this.areColumnsEqual(_,g,h.indexes):false,X=B?this.areColumnsEqual(B,S,h.indexes):false;for(let x of h.foreignKeys){let he=x.referencedTable===s.table,fr=x.referencedTable===a.table;if(!he&&!fr)continue;let Bl=he?c:y,Ve=x.columns[0];Ve&&Ve!==Bl&&(this.data.relationsToDrop.push({table:n,relation:x}),Ve!==c&&Ve!==y&&this.data.columnsToDrop.push({table:n,column:Ve}));}let W={};H||(W[g.databaseName]=g),X||(W[S.databaseName]=W[S.databaseName]||S);for(let x of Object.keys(W))this.data.columnsToAdd.push({table:n,column:W[x]});let ie=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),C=this.buildBelongsToRelation(n,o.model,y,d,void 0,o.onDelete,o.onUpdate),$e=h.foreignKeys.find(x=>x.referencedTable===s.table&&x.columns.length===1&&x.columns[0]===c),ct=h.foreignKeys.find(x=>x.referencedTable===a.table&&x.columns.length===1&&x.columns[0]===y);if(!$e){let x=h.foreignKeys.find(he=>he.referencedTable===s.table);x&&this.data.relationsToDrop.push({table:n,relation:x}),this.data.relationsToAdd.push(ie);}if(!ct){let x=h.foreignKeys.find(he=>he.referencedTable===a.table);x&&this.data.relationsToDrop.push({table:n,relation:x}),this.data.relationsToAdd.push(C);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,m=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,p=w(a.constraintName)||F(o.table,m,a.model().table);s.add(p);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(g=>g.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(S=>S.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(S=>S.columnName===l)?.databaseName||l;let d=o.table,m=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let g=o.relation.model();d=g.table;let S=g.primaryKey||"id";m=g.getColumns().find(B=>B.columnName===S)?.databaseName||S;}let p=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let S=p.has(g.columns[0]),_=g.referencedTable===d,B=g.referencedColumns[0]===m;return S&&_&&B}),y=w(o.relation.constraintName)||F(o.table,l,d),h=e.get(o.table)||new Set;if(c||y&&h.has(y))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let g=w(o.relation.manyToManyOptions.throughModel),S=w(o.relation.manyToManyOptions.leftForeignKey),_=w(o.relation.manyToManyOptions.rightForeignKey),B=o.table===g&&o.relation.columnName===S&&o.relation.model().table===s?.table,H=o.table===g&&o.relation.columnName===_&&o.relation.model().table!==s?.table,X=await this.sql.getTableSchema(g),W=X.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===S&&C.referencedTable===(s?.table||"")),ie=X.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===_&&C.referencedTable===o.relation.model().table);if(B&&W||H&&ie)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 p=a.find(S=>S.columnName===d.foreignKey)?.databaseName||d.foreignKey,c=d.model(),y=c.primaryKey||"id",g=c.getColumns().find(S=>S.columnName===y)?.databaseName||y;return o.relation.columns.length===1&&o.relation.columns[0]===p&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===g})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){return {columnName:e,databaseName:e,isPrimary:false,type:t.type,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?w(n):F(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 pe=class extends T{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var $=class extends T{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var K=class extends T{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 oe=class extends T{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 z=class extends T{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 O=class extends T{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 Ze=class extends T{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var J=class extends O{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 we=class extends T{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 L=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Lt=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);});}},fl=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool("sqlite");if(o)return new Promise((d,m)=>{n.run(i,t,function(p){p&&m(p),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,m)=>{n.all(i,t,(p,c)=>{p&&m(p),(!c||!c.length)&&d([]),d(c);});});let s=r?.typeofModel;if(!s)return new Promise((d,m)=>{n.run(i,t,function(p){p?m(new Error(p.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((p,c)=>{n.run(i,t,function(y){if(y)return c(y);let h=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){p(h);return}let g=h?.[a]||this.lastID;if(!g)return c(new u("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let S=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(S,[g],(_,B)=>{if(_)return c(_);p(B);});});});if(!Array.isArray(r.models))throw new u("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models,m=[];return new Promise(async(p,c)=>{try{let y=d.map(async h=>{let g=new f(s),{columns:S,values:_}=await g.prepareColumns(Object.keys(h),Object.values(h),"insert"),B=Object.fromEntries(S.map((ie,C)=>[ie,_[C]])),H=new b(s,e.getDbType()),{sql:X,bindings:W}=H.parse([new K(new $(s.table),[B])]);return new Promise((ie,C)=>{n.run(X,W,function($e){if($e)return C($e);let ct=h[a]||this.lastID;if(!a){ie(h);return}if(!ct)return C(new u("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let x=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(x,[ct],(he,fr)=>{if(he)return C(he);ie(fr);});});})});m=await Promise.all(y),p(m);}catch(y){c(y);}})}return new Promise((d,m)=>{n.run(i,t,function(p){p?m(new Error(p.message)):d(this.changes);});})};var j=async(i,t,e,r="raw",o)=>{let n=e.type;switch(o?.shouldNotLog||He(i,e.logs,t),n){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool("mysql"),[a]=await as(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="affectedRows"?a.affectedRows:a;case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool("postgres"),d=await as(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?d.rows:d.rowCount;case "sqlite":let m=await as(()=>fl(i,t,e,{typeofModel:o?.sqlLiteOptions?.typeofModel,mode:o?.sqlLiteOptions?.mode||"fetch",models:o?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?Array.isArray(m)?m:[m]:m;default:throw new u("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${n}`)}},jt=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool("mysql"),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),m=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),p=0,c=false,y=false,h=()=>{try{a.release();}catch{}};return m.on("data",g=>{if(o.onData){p++,Promise.resolve(o.onData(l,g)).then(()=>{p--,c&&p===0&&!y&&(h(),l.end());}).catch(S=>{y=true,h(),l.destroy(S);});return}l.write(g);}),m.on("end",()=>{c=true,p===0&&!y&&(h(),l.end());}),m.on("error",g=>{y=true,h(),l.destroy(g);}),l.on("close",()=>{h();}),l}case "cockroachdb":case "postgres":{let s=e.sqlConnection??await e.getPool("postgres").connect(),a=await import('pg-query-stream').catch(()=>{throw new L("pg-query-stream")}),l=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=new a.default(i,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),m=s.query(d),p=0,c=false,y=false,h=g=>{try{s.release(g);}catch{}};return m.on("data",g=>{if(o.onData){p++,Promise.resolve(o.onData(l,g)).then(()=>{p--,c&&p===0&&!y&&(h(),l.end());}).catch(S=>{y=true,h(S),l.destroy(S);});return}l.write(g);}),m.on("end",()=>{c=true,p===0&&!y&&(h(),l.end());}),m.on("error",g=>{y=true,h(g),l.destroy(g);}),l}case "sqlite":{let s=e.sqlConnection??e.getPool("sqlite");return new Lt(s,i,t,{onData:o.onData})}default:throw new u("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function as(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++,Rs(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var E=(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 Y=class extends T{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 Xe=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Wt(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 u("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Ut(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function gl(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var je=i=>typeof i=="number"?i:parseFloat(i);var xe=class extends T{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 Vt=class extends T{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var Ht=class extends T{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var G=class extends T{constructor(e,r,o,n="inner",s,a=false){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;}};var et=class extends T{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 Yt=class extends T{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var zt=class extends T{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var tt=class extends T{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 Jt=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 et(e));}),this}groupByRaw(t){return this.groupByNodes.push(new et(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new tt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new tt(t,"asc",true)),this}limit(t){return typeof t!="number"&&N.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new Yt(t),this}offset(t){return typeof t!="number"&&N.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new zt(t),this}};var Gt=class extends Jt{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new G(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new G(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new G(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new G(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new G(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new G(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,n,s),this}join(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"inner",{operator:s||"="})),this}leftJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"left",{operator:s||"="})),this}rightJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"right",{operator:s||"="})),this}fullJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"full",{operator:s||"="})),this}};var Zt=class extends Gt{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.modelAnnotatedColumns=[];this.dbType=r.getDbType(),this.fromNode=new $(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],e.map(o=>I(o,this.model.databaseCaseConvention)).forEach(o=>{this.selectNodes.push(new Y(o));}),this}selectRaw(e){return this.selectNodes.push(new Y(e,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new $(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes.push(new Y(s,a,n)),this.modelAnnotatedColumns.push(a),this}from(e){return this.fromNode=new $(e),this}table(e){return this.fromNode=new $(e),this}distinct(){return this.distinctNode=new Vt,this}distinctOn(...e){return this.distinctOnNode=new Ht(e),this}};var Xt=class extends Zt{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 R&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||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 R&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 O(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new O(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 O(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new O(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 O(e,"and",false,"in",r)),this):(this.whereNodes.push(new O("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new O(e,"or",false,"in",r)),this):(this.whereNodes.push(new O("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 O(e,"and",true,"in",r)),this):(this.whereNodes.push(new O("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new O(e,"or",true,"in",r)),this):(this.whereNodes.push(new O("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new O(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new O(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new O(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new O(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 O(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 O(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new O(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new O(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new O(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new O(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new O(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 xe(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 xe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new xe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new xe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof R)return e;let r=new R(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new we(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new we(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new R(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ze(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new R(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ze(r.whereNodes,"or");return this.whereNodes.push(o),this}};var er=class extends Xt{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new J(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new J(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new J(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new J(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new J(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new J(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new J(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new J(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new J(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new J(t,"or",false,"raw",e)),this}};var R=class i extends er{constructor(e,r=ne.getInstance()){super(e,r);this.isNestedCondition=false;this.mustRemoveAnnotations=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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);}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return j(e,r,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}})}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 first(){return this.one()}async oneOrFail(){let e=await this.one();if(!e)throw new u("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async firstOrFail(){return this.oneOrFail()}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return await jt(r,o,this.sqlDataSource,e,{onData:(s,a)=>{s.write(a);}})}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:gl(e,a),data:s},{key:r.discriminator,value:d}]}selectSubQuery(e,r){if(typeof e=="function"){let o=new i(this.model,this.sqlDataSource);return e(o),this.selectNodes.push(new Y(o.extractQueryNodes(),r)),this}return this.selectNodes.push(new Y(e.extractQueryNodes(),r)),this}lockForUpdate(e={}){return this.lockQueryNodes.push(new Ge("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Ge("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new De(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new De(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new De(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new De(o,true)),this}async increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}async decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.annotate("count",e,"total");let r=await this.one();return r?je(r.total):0}async getMax(e){this.clearForFunctions(),this.annotate("max",e,"total");let r=await this.one();return r?je(r.total):0}async getMin(e){this.clearForFunctions(),this.annotate("min",e,"total");let r=await this.one();return r?je(r.total):0}async getAvg(e){this.clearForFunctions(),this.annotate("avg",e,"total");let r=await this.one();return r?je(r.total):0}async getSum(e){this.clearForFunctions(),this.annotate("sum",e,"total");let r=await this.one();return r?je(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&N.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),[n,s]=await Promise.all([this.limit(r).offset((e-1)*r).many(),o.getCount("*")]);return {paginationMetadata:Ut(e,r,s),data:n}}from(e,r){if(typeof e=="function"){if(!r)throw new u("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new $(n,r),this}return this.fromNode=new $(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 Le("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 Le("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new u("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 Le("materialized",e,n)),this}async insert(e,r){let{columns:o,values:n}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),s=Object.fromEntries(o.map((m,p)=>[m,n[p]]));this.insertNode=new K(this.fromNode,[s],r);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await j(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});return Array.isArray(d)&&d.length?d[0]:d}async insertMany(e,r){if(!e.length)return [];let o=await Promise.all(e.map(async a=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(a),Object.values(a),"insert");return Object.fromEntries(l.map((m,p)=>[m,d[p]]))}));this.insertNode=new K(this.fromNode,o,r);let{sql:n,bindings:s}=this.astParser.parse([this.insertNode]);return j(n,s,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:o}})}async upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(a.map((y,h)=>[y,l[h]])),{sql:m,bindings:p}=this.astParser.parse([new K(new $(this.model.table),[d],void 0,true),new oe(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await j(m,p,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(c)?c:[c]}async upsertMany(e,r,o,n={updateOnConflict:true}){let s=[];await Promise.all(o.map(async m=>{let{columns:p,values:c}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert"),y=Object.fromEntries(p.map((h,g)=>[h,c[g]]));s.push(y);}));let{sql:a,bindings:l}=this.astParser.parse([new K(new $(this.model.table),s,void 0,true),new oe(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await j(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(d)?d:[d]}async update(e){let r=Object.keys(e),o=Object.values(e),{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new z(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return j(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async truncate(){this.truncateNode=new me(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]);await j(e,r,this.sqlDataSource,"raw");}async delete(){this.deleteNode=new pe(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]);return j(e,r,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async softDelete(e={}){let{column:r="deletedAt",value:o=ae()}=e||{},{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new z(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return j(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return Ds(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new Y("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=yt(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.modelAnnotatedColumns=v(this.modelAnnotatedColumns),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.mustRemoveAnnotations=this.mustRemoveAnnotations,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 Y("*")]),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 E(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await E(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstWithPerformance(e="millis"){return this.oneWithPerformance(e)}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await E(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await E(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await E(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await E(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await E(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await E(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await E(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await E(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await E(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await E(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await E(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var We=class i extends R{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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 Xe(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 first(e){return this.one(e)}async oneOrFail(e){let r=await this.one(e);if(!r)throw new u(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async firstOrFail(e){return this.oneOrFail(e)}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 le(o,this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);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}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();return await jt(r,o,this.sqlDataSource,e,{onData:async(s,a)=>{let l=this.addAdditionalColumnsToModel(a,this.model),d=await le([l],this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),s.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new u(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}async insert(...e){return this.model.insert(...e)}async insertMany(...e){return this.model.insertMany(...e)}async update(e,r={}){return r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),super.update(e)}async softDelete(e={}){let{ignoreBeforeUpdateHook:r=false}=e||{};return !r&&await this.model.beforeUpdate?.(this),super.softDelete(e)}async delete(e={}){return e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),super.delete()}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("count",e,"total");let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("max",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("min",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("avg",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("sum",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),[s,a]=await Promise.all([this.limit(r).offset((e-1)*r).many({ignoreHooks:o.ignoreHooks?["beforeFetch","afterFetch"]:[]}),n.getCount("*",{ignoreHooks:o.ignoreHooks})]);return {paginationMetadata:Ut(e,r,a),data:s}}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],this.selectNodes=this.selectNodes.concat(e.map(r=>new Y(r))),this}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes=this.selectNodes.concat(new Y(s,a,n)),this.modelAnnotatedColumns.push(a),this}removeAnnotations(){return this.mustRemoveAnnotations=true,this.modelAnnotatedColumns=[],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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.whereExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.orWhereExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.whereNotExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.orWhereNotExists(m),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 u(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let y=c[e.foreignKey];y&&n.set(String(y),c);}),r.forEach(c=>{let y=c[this.model.primaryKey];if(!y){c[e.columnName]=null;return}let h=n.get(String(y));c[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new u(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let y=c[e.model.primaryKey];y&&s.set(String(y),c);}),r.forEach(c=>{let y=c[e.foreignKey];if(!y){c[e.columnName]=null;return}let h=s.get(String(y));c[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new u(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let y=c[e.foreignKey];if(!y)return;let h=String(y);a.has(h)||a.set(h,[]),a.get(h).push(c);}),r.forEach(c=>{let y=c[this.model.primaryKey];if(!y){c[e.columnName]=[];return}let h=a.get(String(y))||[];c[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new u(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,m=l.leftForeignKey,p=this.modelColumnsMap.get(m)||this.modelColumnsDatabaseNames.get(m)||I(m,this.model.modelCaseConvention);o.forEach(c=>{let y=c.$annotations||{},h=y[p];if(h==null)return;let g=String(h);d.has(g)||d.set(g,[]),this.modelAnnotatedColumns.includes(p)||(delete y[p],Object.keys(y).length||delete c.$annotations),d.get(g).push(c);}),r.forEach(c=>{let y=c[this.model.primaryKey];if(!y){c[e.columnName]=[];return}let h=d.get(String(y))||[];c[e.columnName]=h;});break;default:throw new u(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=ge.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,m=e.orderByNodes.map(C=>C.isRawValue?C.column:`${this.interpreterUtils.formatStringColumn(this.dbType,C.column)} ${C.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let p=e.with(d,C=>C.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${m}) as rn_${l}`).whereIn(r.foreignKey,n));s&&p.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&p.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(C=>Sr(C,d,e.model.table));return p.select(...c).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new u(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let y=r;if(!o.length)return e;let h=e.limitNode?.limit,g=e.offsetNode?.offset,S=e.modelSelectedColumns.length?e.modelSelectedColumns.map(C=>C.includes(".")?C:`${r.model.table}.${C}`):[`${r.model.table}.*`];if(!h&&!g)return e.select(...S).annotate(`${y.throughModel}.${y.leftForeignKey}`,y.leftForeignKey).leftJoin(y.throughModel,`${y.relatedModel}.${y.model.primaryKey}`,`${y.throughModel}.${y.rightForeignKey}`).whereIn(`${y.throughModel}.${y.leftForeignKey}`,n);let _=ge.randomBytes(6).toString("hex"),B=`${r.model.table}_cte_${_}`,H=e.orderByNodes.map(C=>{if(C.isRawValue)return C.column;let $e=C.column.includes(".")?C.column:`${r.model.table}.${C.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,$e)} ${C.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let X=`${ge.randomBytes(6).toString("hex")}_left_foreign_key`,W=e.with(B,C=>C.select(...S).annotate(`${y.throughModel}.${y.leftForeignKey}`,X).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${y.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,y.leftForeignKey)} ORDER BY ${H}) as rn_${_}`).leftJoin(y.throughModel,`${y.relatedModel}.${y.model.primaryKey}`,`${y.throughModel}.${y.rightForeignKey}`).whereIn(`${y.throughModel}.${y.leftForeignKey}`,n));h&&W.whereRaw(`rn_${_} <= ${h+(g||0)}`),g&&W.whereRaw(`rn_${_} > ${g}`);let ie=S.map(C=>Sr(C,B,e.model.table));return W.select(...ie).annotate(`${B}.${X}`,y.leftForeignKey).from(B);default:throw new u(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new u(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 u(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new u(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 u(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${m}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new u(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}`),m=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${m}`),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 u(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(y=>!y.isRawValue&&y.table===d.throughModel&&y.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let p=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${p} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(p).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new u(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={},n={};return Object.entries(e).forEach(([s,a])=>{if(s==="$annotations"||this.modelColumnsDatabaseNames.get(s)){o[s]=a;return}n[I(s,r.modelCaseConvention)]=a;}),o.$annotations=n,o}async manyWithPerformance(e={},r="millis"){let[o,n]=await E(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await E(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await E(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async firstWithPerformance(e={},r="millis"){return this.oneWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await E(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 E(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await E(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await E(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await E(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await E(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await E(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await E(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var tr=class extends We{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new K(this.fromNode,[o],r?.returning),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new K(this.fromNode,o,r?.returning),this}update(...t){let[e]=t;return this.updateNode=new z(this.fromNode,Object.keys(e),Object.values(e)),this}delete(...t){let[e]=t;return e?.ignoreBeforeDeleteHook||this.model.beforeDelete?.(this),this.deleteNode=new pe(this.fromNode),this}truncate(){return this.truncateNode=new me(this.fromNode),this}softDelete(...t){let[e]=t,{column:r="deletedAt",value:o=ae()}=e||{};return this.updateNode=new z(this.fromNode,[r],[o]),this}};function Tl(i){let t=i.name,e=I(t,"snake");return dd(e)}function bl(){return {}}var rt=class{constructor(t,e){this.model=t,this.modelInstance=bl(),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);}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&&Object.entries(t.where).forEach(([r,o])=>{if(Array.isArray(o)){e.whereIn(r,o);return}e.where(r,o);}),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 u(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new u(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}async insert(t,e={}){!e.ignoreHooks&&await this.model.beforeInsert?.(t);let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),n={};r.forEach((p,c)=>{let y=o[c];n[p]=y,t[p]??(t[p]=y);});let{sql:s,bindings:a}=this.astParser.parse([new K(new $(this.model.table),[n],e.returning)]),l=await j(s,a,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(l,[t],"one",e.returning);let d=l[0];return d?(await this.model.afterFetch?.([d]),await le([d],this.model)):t}async insertMany(t,e={}){let r=[];await this.model.beforeInsertMany?.(t);for(let d of t){let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),c={};m.forEach((y,h)=>{let g=p[h];c[y]=g,d[y]??(d[y]=g);}),r.push(c);}let{sql:o,bindings:n}=this.astParser.parse([new K(new $(this.model.table),r,e.returning)]),s=await j(o,n,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(s,t,"many",e.returning)||[];let a=s;return a.length?(await this.model.afterFetch?.(a),await le(a,this.model)||[]):[]}async upsertMany(t,e,r,o={updateOnConflict:true}){let n=[];await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async d=>{let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),c=Object.fromEntries(m.map((y,h)=>[y,p[h]]));n.push(c);}));let{sql:s,bindings:a}=this.astParser.parse([new K(new $(this.model.table),n,void 0,true),new oe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await j(s,a,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})}async updateRecord(t,e){let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"update"),{primaryKey:n}=this.model;if(!n)throw new u(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");r=r.filter(d=>d!==n),o=o.filter(d=>d!==t[n]);let{sql:s,bindings:a}=this.astParser.parse([new z(new $(this.model.table),r,o),new O(n,"and",false,"=",t[n])]);await j(s,a,this.sqlDataSource,"raw");let l=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!l)throw new u(this.model.name+"::updateRecord","ROW_NOT_FOUND");return l}async deleteRecord(t){if(!this.model.primaryKey)throw new u(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new O(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new pe(new $(this.model.table)),e]);await j(r,o,this.sqlDataSource,"raw");}query(){return new We(this.model,this.sqlDataSource)}dryQuery(){return new tr(this.model,this.sqlDataSource)}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await le([a],this.model):null}return await le(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(m=>m[this.model.primaryKey]),l=a.map(m=>`'${m}'`).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}};var ot=class extends R{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new K(this.fromNode,[o],r),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new K(this.fromNode,o,r),this}upsert(...t){let[e,r,o]=t,n=Object.keys(e),s=Object.keys(r);return this.insertNode=new K(new $(this.model.table),[e],void 0,true),this.onDuplicateNode=new oe(this.model.table,s,n,o?.updateOnConflict??true?"update":"ignore",o?.returning),this}upsertMany(...t){let[e,r,o,n]=t,s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new K(new $(this.model.table),s,void 0,true),this.onDuplicateNode=new oe(this.model.table,e,r,n?.updateOnConflict??true?"update":"ignore",n?.returning),this}update(t){return this.updateNode=new z(this.fromNode,Object.keys(t),Object.values(t)),this}delete(){return this.deleteNode=new pe(this.fromNode),this}truncate(){return this.truncateNode=new me(this.fromNode),this}softDelete(t={}){let{column:e="deletedAt",value:r=ae()}=t||{};return this.updateNode=new z(this.fromNode,[e],[r]),this}};var nt=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??ae()});var ye=class{constructor(t){this.options=t;}static async createDriver(t){throw new u("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var rr=class i extends ye{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(e){let r=await import('mongodb').catch(()=>{throw new L("mongodb")});if(!r)throw new L("mongodb");return new i(r,e)}};var or=class i extends ye{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(e){let r=await import('mysql2/promise').catch(()=>{throw new L("mysql2")});if(!r)throw new L("mysql");return new i(r.default,e)}};var nr=class i extends ye{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(e){let r=await import('pg').catch(()=>{throw new L("pg")});if(!r)throw new L("pg");return new i(r.default,e)}};var sr=class i extends ye{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(e){let r=await import('sqlite3').catch(()=>{throw new L("sqlite3")});if(!r)throw new L("sqlite3");return new i(r.default,e)}};var Ie=class{static async getDriver(t,e){switch(t){case "mysql":case "mariadb":return or.createDriver(e);case "postgres":case "cockroachdb":return nr.createDriver(e);case "sqlite":return sr.createDriver(e);case "mongo":return rr.createDriver(e);default:throw new u(`DriverFactory::getDriver Driver ${t} not found, il likely not installed, try running npm install ${t}`,"DRIVER_NOT_FOUND")}}};var hd=async i=>(await Ie.getDriver(i)).client,st=async(i,t)=>{let e=await hd(i);switch(i){case "mariadb":case "mysql":let r=t;return e.createPool({host:r.host,port:r.port,user:r.username,password:r.password,database:r.database,...r?.driverOptions});case "postgres":case "cockroachdb":let s=t,a=e;return new a.Pool({host:s.host,port:s.port,user:s.username,password:s.password,database:s.database,...s?.driverOptions});case "sqlite":let d=e,m=t?.database;return new d.Database(m,d.OPEN_READWRITE|d.OPEN_CREATE,c=>{if(c)throw new u("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});default:throw new u("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var it=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=ge.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.startTransaction(),t)try{await t(e),await e.commit();}catch(r){throw await e.rollback(),r}return e}async startTransaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mysql":case "mariadb":case "postgres":case "cockroachdb":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 "mysql":case "mariadb":t&&await this.sql.rawQuery(t),await this.sql.sqlConnection.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}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new u("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");N.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){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 "mysql":case "mariadb":await this.sql.sqlConnection.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break}}catch(e){throw N.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new u("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");N.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mysql":case "mariadb":case "postgres":case "cockroachdb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new u("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mysql":case "mariadb":await this.sql.sqlConnection.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;default:throw new u("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw N.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;default:throw new u("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){N.error(t);}await this.sql.closeConnection(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel)return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new u("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new u("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}};var se=class se extends ve{constructor(e){super(e);this.globalTransaction=null;this.models={};this.ownsPool=false;this.sqlConnection=null;this.sqlType=this.type,this.inputDetails=e||{connectionPolicies:{retry:{maxRetries:0,delay:0}},queryFormatOptions:{language:pt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"}},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:pt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"};}static async connect(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new se(e);if(e?.models){let n=o.sanitizeModelKeys(e?.models||{});Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),se.instance=o,await r?.(o),o}static async connectToSecondarySource(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new se(e);if(e?.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),se.instance=o,await r?.(o),o}static async useConnection(e,r){let o=new se(e);if(e.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}o.models=e.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:e.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1");try{await r(o).then(async()=>{o.isConnected&&await o.closeConnection();});}catch(n){throw o.isConnected&&await o.closeConnection(),n}}static getInstance(){if(!se.instance)throw new u("SqlDataSource::getInstance","CONNECTION_NOT_ESTABLISHED");return se.instance}static query(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new R(nt(e,r),n);return r?.alias&&s.from(e,r.alias),s}static dryQuery(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new ot(nt(e,r),n);return r?.alias&&s.from(e,r.alias),s}static createTable(...e){return this.getInstance().createTable(...e)}static alterTable(...e){return this.getInstance().alterTable(...e)}static async startGlobalTransaction(e){return this.getInstance().startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.getInstance().commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.getInstance().rollbackGlobalTransaction();}static async startTransaction(e,r){return this.getInstance().startTransaction(e,r)}static async transaction(e,r){let o=typeof e=="function"?r:e;return this.getInstance().startTransaction(e,o)}static async getTableSchema(e){return this.getInstance().getTableSchema(e)}static async closeConnection(){if(!this.instance){N.warn("Connection already closed");return}await this.instance.closeConnection(),this.instance=null;}static async disconnect(){return this.closeConnection()}static async rawQuery(e,r=[]){let o=this.getInstance();return (o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o).rawQuery(e,r)}static rawStatement(e){return this.getInstance().rawStatement(e)}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async clone(e){let r=new se(this.inputDetails);if(r.sqlType==="sqlite"||!!e?.shouldRecreatePool){if(r.sqlPool=await st(r.sqlType,{type:r.sqlType,host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,connectionPolicies:r.inputDetails.connectionPolicies,queryFormatOptions:r.inputDetails.queryFormatOptions,driverOptions:r.inputDetails.driverOptions,logs:r.logs,models:r.models}),r.ownsPool=true,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}if(r.sqlPool=this.sqlPool,r.ownsPool=false,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}getDbType(){return this.type}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new R(nt(e,r),o);return r?.alias&&n.from(e,r.alias),n}dryQuery(e,r){return new ot(nt(e,r),this)}alterTable(...e){let r=new re(this.getDbType());return r.alterTable(...e),r.queryStatements}createTable(...e){let r=new re(this.getDbType());return r.createTable(...e),r.queryStatements[0]||""}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new it(r,e?.isolationLevel),await this.globalTransaction.startTransaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new u("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){N.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async startTransaction(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 it(n,o?.isolationLevel);if(await s.startTransaction(),typeof e=="function")try{await e(s),await s.commit({throwErrorOnInactiveTransaction:!1});return}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}async transaction(e,r){return this.startTransaction(e,r)}getModelManager(e){if(!this.isConnected)throw new u("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new rt(e,this.globalTransaction.sql):new rt(e,this)}getPool(e=this.sqlType){if(!this.sqlPool)throw new u("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(e=this.sqlType){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new u("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;default:throw new u("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async closeConnection(){if(!this.isConnected){He("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{N.warn("SqlDataSource::closeConnection - Error while rolling back global transaction");}switch(He("Closing connection",this.logs),this.type){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;default:throw new u("SqlDataSource::closeConnection",`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}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 disconnect(){return this.closeConnection()}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){N.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await Ft.makeDiff(this)).getSqlStatements();if(!o.length){N.info("No new changes detected between database schema and models metadata");return}if(N.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);N.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),N.info(`Synced schema with ${o.length} SQL statements`);}async rawQuery(e,r=[]){if(!this.isConnected)throw new u("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let o=yt(this,e);return j(o,r,this,"raw")}rawStatement(e){return new de(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 Cs(Object.values(this.models))}async getTableInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new bt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(a){if(Ye(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=Ce(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(),m=Ce(s,d),p=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof p=="string"?p.toLowerCase()!=="no":typeof p=="boolean"?p:a.notnull!==void 0?a.notnull===0:true,y=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,h=a.char_length!=null?Number(a.char_length):null,g=a.numeric_precision!=null?Number(a.numeric_precision):null,S=a.numeric_scale!=null?Number(a.numeric_scale):null,_=a.timezone!=null?!!a.timezone:typeof a.datetime_precision=="number"?/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase()):/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase());return {name:l,dataType:m,isNullable:c,defaultValue:y,length:h,precision:g,scale:S,withTimezone:_}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new gt(e)]).sql,n=this.getDbType(),s=[];try{s=await this.rawQuery(o);}catch(l){if(Ye(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let m=d.Key_name,p=d.Non_unique===0,c=l.get(m)||{name:m,columns:[],isUnique:p};c.columns.push(d.Column_name),l.set(m,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let m=d.index_name,p=!!d.is_unique,c=l.get(m)||{name:m,columns:[],isUnique:p};c.columns.push(d.column_name),l.set(m,c);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,m=!!l.unique,c=(await this.rawQuery(`PRAGMA index_info(${d})`)).map(y=>y.name);a.push({name:d,columns:c,isUnique:m});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new ht(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(Ye(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let m=Number(d.id),p=l.get(m)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};p.columns.push(String(d.from)),p.referencedColumns.push(String(d.to)),l.set(m,p);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),m=d||`${l.referenced_table}_${l.column_name}`,p=a.get(m)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};p.columns.push(String(l.column_name)),p.referencedColumns.push(String(l.referenced_column)),a.set(m,p);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Tt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(Ye(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 testConnectionQuery(e){await j(e,[],this,"raw",{shouldNotLog:true});}sanitizeModelKeys(e){let r=Object.getOwnPropertyNames(this),o=Object.getOwnPropertyNames(this.constructor),n=[...r,...o];if(Object.keys(e).some(s=>n.includes(s)))throw new u("SqlDataSource::sanitizeModelKeys","DUPLICATE_MODEL_KEYS_WHILE_INSTANTIATING_MODELS",new Error(`Duplicate model keys while instantiating models inside the connection: ${Object.keys(e).filter(s=>n.includes(s)).map(s=>`"${s}"`).join(", ")}`));return e}static get isInGlobalTransaction(){return !!this.instance?.globalTransaction}get isInGlobalTransaction(){return !!this.globalTransaction}get registeredModels(){return this.models}};se.instance=null;var ne=se;var wl=["postgres","cockroachdb"];var at=class at extends Se{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:Tl(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Rl(this)}constructor(){super();}static async all(t={}){return await this.dispatchModelManager(t).find({ignoreHooks:t.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static query(t){return this.dispatchModelManager(t).query()}static dryQuery(t){return this.dispatchModelManager(t).dryQuery()}static async first(t){return this.dispatchModelManager(t).query().one({ignoreHooks:t?.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async find(t,e){return await this.dispatchModelManager(e).find(t)}static async findOneOrFail(t,e){return await this.dispatchModelManager(e).findOneOrFail(t)}static async findOne(t,e){return await this.dispatchModelManager(e).findOne(t)}static async findBy(t,e,r={}){return await this.dispatchModelManager(r).find({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneBy(t,e,r={}){return await this.dispatchModelManager(r).findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneByPrimaryKey(t,e={}){return await this.dispatchModelManager(e).findOneByPrimaryKey(t)}static async refresh(t,e={}){let r=this,o=r.dispatchModelManager(e),n=r.primaryKey,s=t[n],a=await o.findOneByPrimaryKey(s);return a||null}static async insert(t,e={}){return this.dispatchModelManager(e).insert(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static async insertMany(t,e={}){return t.length?this.dispatchModelManager(e).insertMany(t,{ignoreHooks:e.ignoreHooks,returning:e.returning}):[]}static async sync(t,e,r,o,n={}){if(Array.isArray(r)||(r=[r]),!r.length)return;let s=this,l=Wt(s).find(h=>h.columnName===t);if(!l)throw new u(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new u(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=I(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),m=I(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),p=r.map((h,g)=>({[d]:e[s.primaryKey],[m]:h[l.model.primaryKey],...o?o(h,g):{}}));class c extends at{static get table(){return l.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await c.dispatchModelManager(n).insertMany(p);}static async updateRecord(t,e,r={}){try{let o=this,n=o.dispatchModelManager(r);return e&&o.combineProps(t,e),await n.updateRecord(t)}catch(o){throw o instanceof u&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new u(`${this.name}::updateRecord`,"MODEL_HAS_NO_PRIMARY_KEY"):o}}static async firstOrInsert(t,e,r={}){r.fullResponse||(r.fullResponse=false);let n=this.dispatchModelManager(r),s=await n.findOne({where:t});if(s)return r.fullResponse?{isNew:false,model:s}:s;let a=await n.insert(e);return r.fullResponse?{isNew:true,model:a}:a}static async upsert(t,e,r={updateOnConflict:true}){let o=this,n=o.dispatchModelManager(r),s=await n.findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:t});return s?(e[o.primaryKey]=s[o.primaryKey],r.updateOnConflict?await n.updateRecord(e,{returning:r.returning}):s):await n.insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning??["*"]})}static async upsertMany(t,e,r={updateOnConflict:true}){if(!e.length)return [];let o=this,n=o.dispatchModelManager(r);if(!e.every(p=>{let c=new Set(Object.keys(p));return t.every(y=>c.has(y))}))throw new u("Model::upsertMany","CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA");let s=Object.keys(e[0]),a=await n.upsertMany(t,s,e,{ignoreHooks:r.ignoreHooks,returning:r.returning,updateOnConflict:r.updateOnConflict??true}),l=o.sqlInstance.getDbType();if(wl.includes(l))return await le(a,o,r.returning);let d=n.query();r.returning?.length&&d.select(...r.returning);let m=new Map;return t.forEach(p=>{e.forEach(c=>{m.set(p,[...m.get(p)||[],c[p]]);});}),d.where(p=>{t.forEach(c=>{p.orWhereIn(c,m.get(c)||[]);});}),d.many({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async deleteRecord(t,e){return this.dispatchModelManager(e).deleteRecord(t)}static async softDelete(t,e,r){let o=this,{column:n=o.softDeleteColumn,value:s=o.softDeleteValue}=e||{};return t[n]=s,await o.dispatchModelManager({trx:r?.trx,connection:r?.connection}).updateRecord(t),typeof s=="string"?(t[n]=new Date(s),t):(t[n]=s,t)}static async truncate(t={}){return this.dispatchModelManager(t).query().truncate()}static async getTableInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getTableInfo(t.table)}static async getIndexInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getIndexInfo(t.table)}static async getTableSchema(){let t=this;return t.establishConnection(),t.sqlInstance.getTableSchema(t.table)}static combineProps(t,e){for(let r in e)Object.assign(t,{[r]:e[r]});}static getColumns(){return ft(this)}static getRelations(){return Cl(this)}static getIndexes(){return _l(this)}static getUniques(){return Ol(this)}static column(t,...e){A(...e)(this.prototype,t);}static hasOne(t,...e){Nl(...e)(this.prototype,t);}static hasMany(t,...e){Ml(...e)(this.prototype,t);}static belongsTo(t,...e){Sl(...e)(this.prototype,t);}static manyToMany(t,...e){ql(...e)(this.prototype,t);}static establishConnection(){let t=ne.getInstance();if(!t)throw new u("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){if(t?.connection)return t.connection.getModelManager(this);if(t?.trx)return t.trx.sql.getModelManager(this);let e=this;return e.establishConnection(),e.sqlInstance.getModelManager(e)}async save(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new u(r.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s={[o]:n},{[o]:a,...l}=e,d=await r.upsert(s,l,{updateOnConflict:true,...t});return r.combineProps(this,d),this}async update(t,e={}){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new u(o.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new u(o.name+"::update","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.updateRecord(r,t,e);}async softDelete(t,e){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new u(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new u(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.softDelete(r,t,e);}async delete(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new u(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new u(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await r.deleteRecord(this,t);}async refresh(t){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new u(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new u(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY_VALUE");let s=await r.refresh(this,t);return r.combineProps(this,s),this}};at.softDeleteColumn="deletedAt",at.softDeleteValue=ae();var Z=at;var fe=class{constructor(t,e){this.model=Z;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var ir=class extends fe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var ar=class extends fe{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var lr=class extends fe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var dr=class extends fe{constructor(e,r,o){super(e,r);this.type="manyToMany";this.primaryModel=o.primaryModel,this.relatedModel=e.table,this.throughModel=o.throughModel,this.leftForeignKey=o.leftForeignKey,this.rightForeignKey=o.rightForeignKey;}};function cR(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=P.getMetadata(Pt,e.prototype)||[];o.push({columns:r,name:t??Bt(e.table,r.join("_"))}),P.defineMetadata(Pt,o,e.prototype);}}function mR(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=P.getMetadata(Et,e.prototype)||[];o.push({columns:r,name:t??ee(e.table,r.join("_"))}),P.defineMetadata(Et,o,e.prototype);}}function pR(i){return t=>{let e=t,r=e.query;e.query=function(...o){let n=r.bind(this).call(this,...o);return i(n),n};}}function A(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(P.getMetadata(It,e))throw new u("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");P.defineMetadata(It,r,e);}let n=i.databaseName??I(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??Me(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}},a=P.getMetadata(xt,e)||[];a.push(s),P.defineMetadata(xt,a,e);}}A.primary=bd;A.date=_d;A.boolean=Rd;A.json=Od;A.uuid=Nd;A.ulid=Md;A.integer=Sd;A.float=wd;A.encryption={symmetric:qd,asymmetric:Cd};function bd(i={}){return A({...i,primaryKey:true})}function wd(i={}){return A({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseFloat(t)}})}function Sd(i={}){return A({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)}})}function Nd(i={}){return A({type:"uuid",...i,prepare:t=>t||ge.randomUUID()})}function Md(i={}){return A({type:"ulid",...i,prepare:t=>t||qs()})}function qd(i){return A({...i,prepare:t=>t&&ws(i.key,t),serialize:t=>t&&Ss(i.key,t)})}function Cd(i){return A({...i,prepare:t=>t&&Ns(i.publicKey,t),serialize:t=>t&&Ms(i.privateKey,t)})}function Rd(i={}){return A({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t})}function _d(i={}){let{format:t="ISO",timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i;return A({type:"datetime",...n,autoUpdate:r,prepare:s=>s?r?mt(new Date,t,e):typeof s=="string"?s:mt(s,t,e):o?mt(new Date,t,e):null,serialize:s=>{if(s!==void 0)return s===null?null:bs(s,t,e)}})}function Od(i={}){return A({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t})}function ft(i){try{return P.getMetadata(xt,i.prototype)||[]}catch{return []}}function Sl(i,t,e){return (r,o)=>{let n=()=>Ne(i().table),s=()=>{let d=r.constructor.table,m=t||n();return F(d,m,i().table)},a={type:"belongsTo",columnName:o,model:i,foreignKey:t?String(t):n,constraintName:e?.constraintName??s,onUpdate:e?.onUpdate,onDelete:e?.onDelete},l=P.getMetadata(te,r)||[];l.push(a),P.defineMetadata(te,l,r);}}function Nl(i,t){return (e,r)=>{let o=()=>Ne(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=P.getMetadata(te,e)||[];s.push(n),P.defineMetadata(te,s,e);}}function Ml(i,t){return (e,r)=>{let o=()=>Ne(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=P.getMetadata(te,e)||[];s.push(n),P.defineMetadata(te,s,e);}}function ql(i,t,e,r){return (o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",d=typeof t=="string"?t:()=>t().table,m=o.constructor.table,p=()=>Ne(m),c=()=>Ne(i().table),y=()=>F(w(d),s?String(s):p()),h={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??y,foreignKey:s?String(s):p,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:m,throughModel:d,leftForeignKey:s?String(s):p,rightForeignKey:a?String(a):c,wasModelProvided:l}},g=P.getMetadata(te,o)||[];g.push(h),P.defineMetadata(te,g,o);}}function Cl(i){return P.getMetadata(te,i.prototype)||[]}function Wt(i){return (P.getMetadata(te,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=w(s),l=o();switch(r){case "belongsTo":return new ir(l,n,a);case "hasOne":return new lr(l,n,a);case "hasMany":return new ar(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new u("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new dr(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:w(e.manyToManyOptions.throughModel),leftForeignKey:w(e.manyToManyOptions.leftForeignKey),rightForeignKey:w(e.manyToManyOptions.rightForeignKey)});default:throw new u("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Rl(i){return P.getMetadata(It,i.prototype)}function _l(i){return P.getMetadata(Pt,i.prototype)||[]}function Ol(i){return P.getMetadata(Et,i.prototype)||[]}var ds=class{constructor(t,e){this.typeofModel=t,this.modelData=e;}merge(t){this.modelData={...this.modelData,...t};}async create(t){let e=this.typeofModel;if(t===1)return e.insert(this.modelData);let r=Array.from({length:t});return e.insertMany(r.map(()=>({...this.modelData})))}},Dd=(i,t)=>new ds(i,t);var lt=class extends Z{};U([A.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"createdAt"),U([A.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"updatedAt"),U([A.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"deletedAt");var us=class extends Z{};U([A.uuid({type:"uuid",primaryKey:true,openApi:{type:"string",format:"uuid",required:true}})],us.prototype,"id");var cs=class extends Z{};U([A.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],cs.prototype,"id");var Pe=class extends Z{};U([A.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Pe.prototype,"id"),U([A({type:"varchar",length:255,openApi:{type:"string",required:true}})],Pe.prototype,"email"),U([A.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Pe.prototype,"createdAt"),U([A.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Pe.prototype,"updatedAt"),U([A.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Pe.prototype,"deletedAt");var{plural:xd}=dd;function Dl(i){let t=i.name,e=I(t,"snake");return xd(e)}function Al(){return {$annotations:{}}}var Ue=class extends Se{static get collection(){return this._collection||Dl(this)}static query(t={}){return this.dispatchModelManager(t).query()}static rawCollection(){return this.mongoInstance.getCurrentConnection().db().collection(this.collection)}static async find(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).find(t)}static async findOne(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOne(t)}static async findOneOrFail(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOneOrFail(t)}static async insert(t,e={}){return await this.dispatchModelManager(e).insert(t)}static async insertMany(t,e={}){return await this.dispatchModelManager(e).insertMany(t)}static async updateRecord(t,e={}){return await this.dispatchModelManager(e).updateRecord(t)}static async deleteRecord(t,e={}){await this.dispatchModelManager(e).deleteRecord(t);}static establishConnection(){let t=dt.getInstance();if(!t)throw new u("Collection::establishConnection","CONNECTION_NOT_ESTABLISHED");this.mongoInstance=t;}static dispatchModelManager(t){if(t.useConnection)return t.useConnection.getModelManager(this,t.useConnection);if(t.session)return this.mongoInstance.getModelManager(this,this.mongoInstance,t.session);let e=this;return e.establishConnection(),e.mongoInstance.getModelManager(e,e.mongoInstance)}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static property(t){gr()(this.prototype,t);}static async afterFetch(t){return t}};U([gr()],Ue.prototype,"id");async function Re(i,t,e){if(!t)return null;let r=Al(),o=Ts(i);return (!e||!e.length)&&(e=o),e.includes("id")||e.push("id"),r.$annotations||(r.$annotations={}),await Promise.all(Object.keys(t).map(async n=>{if(n==="_id"){r.id=t._id?.toString();return}if(!o.includes(n)){let a=I(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=I(n,i.modelCaseConvention);r[s]=t[n];})),Object.keys(r.$annotations).length||delete r.$annotations,await Promise.all(e.map(async n=>{if(n!=="id"&&!t.hasOwnProperty(n)){let s=I(n,i.modelCaseConvention);r[s]=null;}})),r}async function ur(i,t,e){return (await Promise.all(t.map(async o=>await Re(i,o,e)))).filter(o=>o!==null)}var cr=class{constructor(t,e,r,o=false){this.model=t,this.idObject={},this.whereObject={},this.logs=o,this.session,this.mongoDataSource=e,this.collection=this.mongoDataSource.getCurrentConnection().db().collection(this.model.collection);}async one(t={throwErrorOnNull:false}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.findOne(e,{projection:this.selectObject,limit:1,session:this.session}),o=await Re(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await this.model.afterFetch([o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new u("MongoQueryBuilder::oneOrFail","ROW_NOT_FOUND");return e}async many(t={}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.find(e,{projection:this.selectFields,sort:this.sortObject,limit:this.limitNumber,skip:this.offsetNumber,session:this.session}).toArray(),o=await ur(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await this.model.afterFetch(o)}async insert(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertOne(t,{session:this.session});if(!e.returning)return {id:r.insertedId.toString()};let o=await this.collection.findOne({_id:r.insertedId});return await Re(this.model,o,this.selectFields)}async insertMany(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertMany(t,{session:this.session});if(!e.returning)return Object.values(r.insertedIds).map(n=>({id:n.toString()}));let o=await this.collection.find({_id:{$in:Object.values(r.insertedIds)}}).toArray();return await ur(this.model,o,this.selectFields)}async update(t,e={}){if(e.ignoreHooks||this.model.beforeUpdate(this),(await this.collection.updateMany({_id:this.idObject,...this.whereObject},{$set:t,session:this.session})).modifiedCount===0)return [];let o=await this.collection.find({_id:Object.keys(this.idObject).length?this.idObject:void 0,...this.whereObject},{projection:this.selectFields}).toArray();return await ur(this.model,o,this.selectFields)}async delete(t={}){t.ignoreHooks||this.model.beforeDelete(this),await this.collection.deleteMany(this.whereObject,{session:this.session});}async count(t={}){return t.ignoreHooks||this.model.beforeFetch(this),this.collection.countDocuments(this.whereObject,{session:this.session})}select(t){return this.selectFields=t,this.selectObject=t.reduce((e,r)=>(e[r]=1,e),{}),this}where(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=V("mongodb");if(t==="id")return this.idObject={$eq:new s.ObjectId(n)},this;let a={[t]:{[o]:n}};return this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this}andWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=V("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this)}orWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=V("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(a)):this.whereObject={$or:[a]},this)}whereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereRaw(t){return this.whereObject={...this.whereObject,...t},this}andRawWhere(t){return this.whereObject={...this.whereObject,...t},this}orRawWhere(t){return this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(t),this}sortById(t){return this.sortObject={_id:t},this}sort(t){return typeof t=="number"?(this.sortObject={_id:t},this):typeof t=="string"?(this.sortObject={[t]:1},this):Array.isArray(t)?(this.sortObject=t.reduce((e,r)=>{if(typeof r=="string")return e[r]=1,e;let o=Object.keys(r)[0],n=Object.values(r)[0];return e[o]=+n,e},{}),this):(this.sortObject=t,this)}limit(t){return this.limitNumber=t,this}offset(t){return this.offsetNumber=t,this}};var mr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=Ue,this.mongoClient=this.mongoDataSource.getCurrentConnection(),this.collectionInstance=this.mongoClient.db().collection(this.collection.collection);}async find(t){let e=this.query();return t?(t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),t.sort&&e.sort(t.sort),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),e.many({ignoreHooks:t.ignoreHooks})):e.many()}async findOne(t){let e=this.query();return t?(t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),e.one({ignoreHooks:t.ignoreHooks})):e.oneOrFail()}async findOneOrFail(t){let e=this.query();if(!t)return e.oneOrFail();t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([o,n])=>{e.where(o,n);});let r=await e.one({ignoreHooks:t.ignoreHooks});if(r===null)throw t.customError?t.customError:new u("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new cr(this.collection,this.mongoDataSource,this.session,this.logs)}async insert(t,e={}){e.ignoreHooks||this.collection.beforeInsert(t);let o=(await this.collectionInstance.insertOne(t)).insertedId,n=await this.collectionInstance.findOne({_id:o},{session:this.session});return await Re(this.collection,n)}async insertMany(t,e={}){e.ignoreHooks||t.forEach(s=>{this.collection.beforeInsert(s);});let o=(await this.collectionInstance.insertMany(t)).insertedIds,n=await this.collectionInstance.find({_id:{$in:Object.values(o)}},{session:this.session}).toArray();return Promise.all(n.map(async s=>await Re(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new u("CollectionManager::updateRecord","ROW_NOT_FOUND");let r=await import('mongodb');if((await this.collectionInstance.updateOne({_id:new r.ObjectId(e)},{$set:t})).modifiedCount===0)throw new u("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Re(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new u("CollectionManager::deleteRecord","ROW_NOT_FOUND");let r=await import('mongodb');return await this.collectionInstance.deleteOne({_id:new r.ObjectId(e)},{session:this.session}),t}};var Ee=class Ee extends ve{constructor(t,e){super({type:"mongo"}),this.url=t,this.isConnected=false,this.mongoClient=e;}getCurrentConnection(){return this.mongoClient}static async connect(t,e,r){if(!t&&(t=M.MONGO_URL,!t))throw new u("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let o=(await Ie.getDriver("mongo")).client,n=new o.MongoClient(t,e);return await n.connect(),this.instance=new Ee(t,n),this.instance.isConnected=true,this.instance.logs=e?.logs||M.MONGO_LOGS||false,await r?.(this.instance),this.instance}static getInstance(){if(!Ee.instance)throw new u("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Ee.instance}startSession(){let t=this.mongoClient.startSession();return t.startTransaction(),t}static async disconnect(){if(!this.instance)throw new u("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(t,e){let r=(await Ie.getDriver("mongo")).client,o=new r.MongoClient(t.url,t.options);await o.connect();let n=new Ee(t.url,o);await e(n),await o.close();}static query(t){return this.getInstance().query(t)}query(t){if(!this.isConnected)throw new u("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:t},this).query()}getModelManager(t,e,r){return new mr(t,e,r,this.logs)}};Ee.instance=null;var dt=Ee;var Q=class Q{constructor(t){this.OK="OK";this.isConnected=false,this.ioRedisConnection=t;}static get ioredis(){return this.redisDataSourceInstance.ioRedisConnection}get ioredis(){return this.ioRedisConnection}static async connect(t){if(this.isConnected)return;let e=t?.port||+M.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new L("ioredis")});this.redisDataSourceInstance=new Q(new r.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:e,password:t?.password||M.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new u("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new L("ioredis")}),r=new e.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:t?.port||+M.REDIS_PORT||6379,password:t?.password||M.REDIS_PASSWORD,...t}),o=new Q(r);return await o.ioRedisConnection.ping(),o.isConnected=true,o}static async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.redisDataSourceInstance.ioRedisConnection.setex(t,r,e);return}await this.redisDataSourceInstance.ioRedisConnection.set(t,e);}catch{throw new u("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new u("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new u("RedisDataSource::getBuffer","GET_FAILED")}}static async consume(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return await this.redisDataSourceInstance.ioRedisConnection.del(t),this.getValue(e)}catch{throw new u("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new u("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new u("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new u("RedisDataSource::disconnect","DISCONNECT_FAILED")}}async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.ioRedisConnection.setex(t,r,e);return}await this.ioRedisConnection.set(t,e);}catch{throw new u("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return Q.getValue(e)}catch{throw new u("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new u("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),Q.getValue(e)}catch{throw new u("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new u("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new u("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new u("RedisDataSource::disconnect","DISCONNECT_FAILED");N.warn("RedisDataSource::disconnect DISCONNECT_FAILED");}}static async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.lpush(t,...r)}catch{throw new u("RedisDataSource::lpush","LPUSH_FAILED")}}static async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.rpush(t,...r)}catch{throw new u("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new u("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new u("RedisDataSource::rpop","RPOP_FAILED")}}static async lrange(t,e,r){try{return (await this.redisDataSourceInstance.ioRedisConnection.lrange(t,e,r)).map(n=>this.getValue(n)).filter(n=>n!==null)}catch{throw new u("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new u("RedisDataSource::llen","LLEN_FAILED")}}async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.lpush(t,...r)}catch{throw new u("RedisDataSource::lpush","LPUSH_FAILED")}}async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.rpush(t,...r)}catch{throw new u("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return Q.getValue(e)}catch{throw new u("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return Q.getValue(e)}catch{throw new u("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>Q.getValue(n)).filter(n=>n!==null)}catch{throw new u("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new u("RedisDataSource::llen","LLEN_FAILED")}}static async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.hset(t,e,r)}catch{throw new u("RedisDataSource::hset","HSET_FAILED")}}static async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.redisDataSourceInstance.ioRedisConnection.hmset(t,r)}catch{throw new u("RedisDataSource::hmset","HMSET_FAILED")}}static async hget(t,e){try{let r=await this.redisDataSourceInstance.ioRedisConnection.hget(t,e);return this.getValue(r)}catch{throw new u("RedisDataSource::hget","HGET_FAILED")}}static async hgetall(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=this.getValue(n);return r}catch{throw new u("RedisDataSource::hgetall","HGETALL_FAILED")}}static async hmget(t,...e){try{return (await this.redisDataSourceInstance.ioRedisConnection.hmget(t,...e)).map(o=>this.getValue(o))}catch{throw new u("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new u("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new u("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new u("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new u("RedisDataSource::hlen","HLEN_FAILED")}}async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.ioRedisConnection.hset(t,e,r)}catch{throw new u("RedisDataSource::hset","HSET_FAILED")}}async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.ioRedisConnection.hmset(t,r)}catch{throw new u("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return Q.getValue(r)}catch{throw new u("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=Q.getValue(n);return r}catch{throw new u("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>Q.getValue(o))}catch{throw new u("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new u("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new u("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new u("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new u("RedisDataSource::hlen","HLEN_FAILED")}}static async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.sadd(t,...r)}catch{throw new u("RedisDataSource::sadd","SADD_FAILED")}}static async smembers(t){try{return (await this.redisDataSourceInstance.ioRedisConnection.smembers(t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::smembers","SMEMBERS_FAILED")}}static async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.srem(t,...r)}catch{throw new u("RedisDataSource::srem","SREM_FAILED")}}static async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.redisDataSourceInstance.ioRedisConnection.sismember(t,e)}catch{throw new u("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new u("RedisDataSource::scard","SCARD_FAILED")}}static async sinter(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sinter(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sinter","SINTER_FAILED")}}static async sunion(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sunion(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sunion","SUNION_FAILED")}}static async sdiff(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sdiff(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sdiff","SDIFF_FAILED")}}async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.sadd(t,...r)}catch{throw new u("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::smembers","SMEMBERS_FAILED")}}async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.srem(t,...r)}catch{throw new u("RedisDataSource::srem","SREM_FAILED")}}async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.ioRedisConnection.sismember(t,e)}catch{throw new u("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new u("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sdiff","SDIFF_FAILED")}}static async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.redisDataSourceInstance.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new u("RedisDataSource::zadd","ZADD_FAILED")}}static async zrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrange","ZRANGE_FAILED")}}static async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}static async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.zrem(t,...r)}catch{throw new u("RedisDataSource::zrem","ZREM_FAILED")}}static async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.redisDataSourceInstance.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new u("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new u("RedisDataSource::zcard","ZCARD_FAILED")}}async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new u("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Q.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrange(t,e,r),n.map(s=>Q.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Q.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrevrange(t,e,r),n.map(s=>Q.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.zrem(t,...r)}catch{throw new u("RedisDataSource::zrem","ZREM_FAILED")}}async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new u("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new u("RedisDataSource::zcard","ZCARD_FAILED")}}static async subscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.subscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("message",e);}catch{throw new u("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new u("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}static async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.redisDataSourceInstance.ioRedisConnection.publish(t,r)}catch{throw new u("RedisDataSource::publish","PUBLISH_FAILED")}}static async psubscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.psubscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new u("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new u("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new u("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new u("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.ioRedisConnection.publish(t,r)}catch{throw new u("RedisDataSource::publish","PUBLISH_FAILED")}}async psubscribe(t,e){try{await this.ioRedisConnection.psubscribe(...t),this.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new u("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new u("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new u("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new u("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new u("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new u("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new u("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new u("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new u("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new u("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new u("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new u("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new u("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new u("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new u("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new u("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new u("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new u("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new u("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new u("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new u("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new u("RedisDataSource::type","TYPE_FAILED")}}static getValue(t){if(!t)return null;try{return JSON.parse(t)}catch{}return t==="true"||t==="false"?!!t:Number.isNaN(Number(t))?t:Number(t)}};Q.OK="OK";var ms=Q;var ps=class{constructor(t){this.dbType=t,this.migrationName=ut.basename(fileURLToPath(import.meta.url)),this.schema=new re(this.dbType);}};async function Il(i,t){let e=ut.isAbsolute(i)?i:ut.resolve(process.cwd(),i),{mod:r}=await bundleRequire({filepath:e,format:"esm",preserveTemporaryFile:false,esbuildOptions:{keepNames:true,sourcemap:true},tsconfig:"./tsconfig.json",external:["ioredis","mongodb","pg","mysql2","sqlite3","bundle-require","esbuild","sql-formatter","sql-highlight","reflect-metadata","pluralize","dayjs","async-mutex","commander"]});return r}var ys=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return Object.values(r).map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.map(n=>n.table_name);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
|
|
83
|
+
ORDER BY pk`,bindings:[]}}},el=new Jn;var Gn=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},tl=new Gn;var Zn=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new 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}"`:""}},rl=new Zn;var Xn=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:[]}}},ol=new Xn;var es=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}}},nl=new es;var ts=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 de?`${r.formatStringColumn("sqlite",a)} = ${d.rawValue}`:(n.push(d),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},sl=new ts;var rs=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}},il=new rs;var os=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}}},al=new os;var ns=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}}},ll=new ns;var ss=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}}},dl=new ss;var is=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}}},ul=new is;var cl={mysql:{alter_table:{add_column:As,add_constraint:xs,add_primary_key:Is,alter_column_type:Ps,alter_table:Es,drop_column:Bs,drop_constraint:$s,drop_default:vs,drop_not_null:Ks,drop_primary_key:Qs,rename_column:ks,rename_table:Fs,set_default:Ls,set_not_null:js},column:{column_type:Ws},constraint:{after:Us,constraint:Vs},create_table:{create_table:Hs},delete:{delete:Ys},distinct:{distinct:zs,distinct_on:Js},drop_table:{drop_table:Gs},from:{from:Zs},group_by:{group_by:Xs},having:{having:ei},index_op:{create_index:ti,drop_index:ri},insert:{insert:oi},join:{join:ni},limit:{limit:si},lock:{lock:ii},offset:{offset:ai},on_duplicate:{on_duplicate:li},order_by:{order_by:di},raw:{raw:ui},schema:{foreign_key_info:ci,index_info:mi,primary_key_info:pi,table_info:yi},select:{select:fi},truncate:{truncate:hi},union:{union:gi},update:{update:Ti},where:{where:bi,where_group:wi,where_json:Si,where_subquery:Ni},with:{with:Mi}},postgres:{alter_table:{add_column:qi,add_constraint:Ci,add_primary_key:Ri,alter_column_type:_i,alter_table:Oi,drop_column:Di,drop_constraint:Ai,drop_default:xi,drop_not_null:Ii,drop_primary_key:Pi,rename_column:Ei,rename_table:Bi,set_default:$i,set_not_null:vi},column:{column_type:Ki},constraint:{after:Qi,constraint:ki},create_table:{create_table:Fi},delete:{delete:Li},distinct:{distinct:ji,distinct_on:Wi},drop_table:{drop_table:Ui},from:{from:Vi},group_by:{group_by:Hi},having:{having:Yi},index_op:{create_index:zi,drop_index:Ji},insert:{insert:Gi},join:{join:Zi},limit:{limit:Xi},lock:{lock:ea},offset:{offset:ta},on_duplicate:{on_duplicate:ra},order_by:{order_by:oa},raw:{raw:na},schema:{foreign_key_info:sa,index_info:ia,primary_key_info:aa,table_info:la},select:{select:da},truncate:{truncate:ua},union:{union:ca},update:{update:ma},where:{where:pa,where_group:ya,where_json:fa,where_subquery:ha},with:{with:ga}},sqlite:{alter_table:{add_column:Ta,add_constraint:ba,alter_column_type:wa,alter_table:Sa,drop_column:Na,drop_constraint:Ma,drop_default:qa,drop_not_null:Ca,drop_primary_key:Ra,rename_column:_a,rename_table:Oa,set_default:Da,set_not_null:Aa},column:{column_type:xa},constraint:{after:Ia,constraint:Pa},create_table:{create_table:Ea},delete:{delete:Ba},distinct:{distinct:$a,distinct_on:va},drop_table:{drop_table:Ka},from:{from:Qa},group_by:{group_by:ka},having:{having:Fa},index_op:{create_index:La,drop_index:ja},insert:{insert:Wa},join:{join:Ua},limit:{limit:Va},lock:{lock:Ha},offset:{offset:Ya},on_duplicate:{on_duplicate:za},order_by:{order_by:Ja},raw:{raw:Ga},schema:{foreign_key_info:Za,index_info:Xa,primary_key_info:el,table_info:tl},select:{select:rl},truncate:{truncate:ol},union:{union:nl},update:{update:sl},where:{where:il,where_group:al,where_json:ll,where_subquery:dl},with:{with:ul}}};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(p=>!!p&&p.folder==="distinctOn"),n=!o&&t.find(p=>!!p&&p.folder==="distinct"),s=t.filter(p=>p!==null&&p.folder!=="distinct"&&p.folder!=="distinctOn"),a=[],l=[],d=null;for(let p=0;p<s.length;p++){let c=s[p];c.currParamIndex=e+l.length;let y=cl[this.mapCommonDbType(this.dbType)][c.folder][c.file];if(!y)throw new Error(`Interpreter not found for ${this.dbType} ${c.keyword}`);y.model=this.model;let h=y.toSql(c);if(!h.sql||!h.sql.trim().length)continue;let g=s[p+1],_=!g||g.keyword!==c.keyword?"":g.chainsWith;if(c.folder==="lock"||c.folder==="on_duplicate"||c.folder==="schema"){a.push(`${h.sql}${_}`),l.push(...h.bindings),d=c.keyword;continue}if(d!==c.keyword||c.canKeywordBeSeenMultipleTimes){if(r)a.push(`${h.sql}${_}`);else {let B=c.keyword;if(c.folder==="with"){let H=p,X=false;for(;H<s.length&&s[H].keyword===c.keyword;){let W=s[H];if(W.folder==="with"&&W.clause==="recursive"){X=true;break}H++;}X&&(B=`${B} recursive`);}if(B==="select")if(o){let H=Array.isArray(o.columns)?o.columns.join(", "):"";a.push(`select distinct on (${H}) ${h.sql}${_}`);}else n?a.push(`select distinct ${h.sql}${_}`):a.push(`select ${h.sql}${_}`);else a.push(`${B} ${h.sql}${_}`);}d=c.keyword;}else a.push(`${h.sql}${_}`);l.push(...h.bindings);}return {sql:a.join(" "),bindings:l}}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}};var ht=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var gt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Tt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var bt=class extends T{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var wt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ue=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var ke=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var St=class extends T{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var Te=class extends T{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 Nt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var ce=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var ze=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var Mt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var Fe=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var qt=class extends T{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var Ct=class extends T{constructor(e){super("rename to");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="rename_table";this.newName=e;}};var Je=class extends T{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var Rt=class extends T{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var k=class extends T{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 _t=class extends T{constructor(e,r=[],o=[],n=false){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;}};var Ot=class extends T{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 Dt=class extends T{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 At=class extends T{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 me=class extends T{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var xt=Symbol("columns"),It=Symbol("primaryKey"),te=Symbol("relations"),Pt=Symbol("indexes"),Et=Symbol("uniques"),Ne=i=>`${dd.singular(i)}_id`,Bt=(i,t)=>`idx_${i}_${t}`,ee=(i,t)=>`uq_${i}_${t}`,F=(i,t,e)=>`fk_${i}_${t}${e?`_${e}`:""}`,Me=(i,t)=>`pk_${i}_${t}`;var D=class extends T{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.isRawValue=o.isRawValue??false;}};var Ge=class extends T{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 De=class extends T{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 Le=class extends T{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 qe=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var $t=class extends T{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var vt=class extends qe{constructor(t,e,r,o,n=[],s="create_table"){super(e),this.columnNode=r,this.tableName=o,this.namedConstraints=n,this.context=s,this.sqlType=t;}primaryKey(t){let e=Me(this.tableName,w(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new k("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new k("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??F(this.tableName??"",w(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new k("foreign_key",{columns:[w(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new k("foreign_key",{columns:[w(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 k("not_null",{columns:[w(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new k("null",{columns:[w(this.columnNode.column)]})),this}default(t){let e;return t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new k("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new k("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName??ee(this.tableName??"",w(this.columnNode.column))})),this):(this.namedConstraints.push(new k("unique",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName||ee(this.tableName??"",w(this.columnNode.column))})),this)}after(t){return this.nodes.push(new $t(t)),this}handleSqliteAutoIncrement(t){return this.nodes.push(new k("primary_key",{columns:[w(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Ae=class extends qe{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}build(e){return this.nodes.push(e),new vt(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}char(e,r=1){let o=new D(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new D(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new D(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 D(e,"uuid");return this.build(r)}ulid(e){let r=new D(e,"ulid");return this.build(r)}integer(e,r=255){let o=new D(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new D(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new D(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new D(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new D(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new D(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new D(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new D(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new D(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new D(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 D(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new D(e,"time",{precision:r});return this.build(o)}year(e){let r=new D(e,"year");return this.build(r)}datetime(e,r){let o=new D(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}timestamp(e,r){let o=new D(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision});return this.build(o)}boolean(e){let r=new D(e,"boolean");return this.build(r)}binary(e){let r=new D(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new D(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new D(e,"blob");return this.build(r)}tinyblob(e){let r=new D(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new D(e,"mediumblob");return this.build(r)}longblob(e){let r=new D(e,"longblob");return this.build(r)}json(e){let r=new D(e,"json");return this.build(r)}jsonb(e){let r=new D(e,"jsonb");return this.build(r)}enum(e,r){let o=new D(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new D(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new D(e,"",{isRawValue:true});return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Kt=class extends qe{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}addColumn(t){let e=[],r=new Ae(this.sqlType,e,this.table),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(p=>p.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(p=>{let c=p;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),d=new wt(a);d.inlineConstraints=l,this.nodes.push(d),o.getNodes().filter(p=>{let c=p;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(p=>{this.nodes.push(new ue(p));});}alterColumn(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Ae(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(c=>c.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=w(s.column),l=o.getNodes().find(c=>c.constraintType==="null"),m=o.getNodes().find(c=>c.constraintType==="not_null")||l,p=o.getNodes().find(c=>c.constraintType==="default");this.nodes.push(new St(w(a),s,{})),m&&(m.constraintType==="not_null"?this.nodes.push(new Rt(w(a))):m.constraintType==="null"&&this.nodes.push(new Mt(w(a)))),p&&(p.defaultValue===void 0||p.defaultValue===null?this.nodes.push(new ze(w(a))):this.nodes.push(new Je(w(a),p.defaultValue))),o.getNodes().forEach(c=>{let y=c;switch(y.constraintType){case "primary_key":this.addPrimaryKey(w(a));break;case "unique":this.unique(w(a),{constraintName:y.constraintName});break;case "foreign_key":this.addForeignKey(w(a),y.references?.table??"",w(y.references?.columns?.[0]??""),{constraintName:y.constraintName,onDelete:y.onDelete,onUpdate:y.onUpdate});break}});}dropColumn(t){this.nodes.push(new Nt(t));}renameColumn(t,e){this.nodes.push(new qt(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ze(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ke([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ue(new k(...t)));}addForeignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ue(new k("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??F(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ue(new k("unique",{columns:[t],constraintName:e?.constraintName??ee(this.table,t)})));}setDefault(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new Je(t,e));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=F(this.table,t,e);this.nodes.push(new ce(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new u("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??ee(this.table,t);this.nodes.push(new ce(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ce(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new u("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new u("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new Fe(t));}};var re=class{constructor(t){if(this.sqlType=t||M.DB_TYPE,!this.sqlType)throw new u("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawQuery(t){this.queryStatements.push(t);}runFile(t){if(!ml.existsSync(t))throw new u("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=ut.basename(t),r=ut.extname(e);if(r!==".sql"&&r!==".txt")throw new u("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=ml.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 Ae(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new b({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a=new _t(t,n,o.getNamedConstraints(),r?.ifNotExists),l=s.parse([a]).sql,d=l.startsWith("create table")?l:`create table ${l}`;this.rawQuery(d);}alterTable(t,e){let r=[],o=new Kt(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 l=new Te(t,s),d=n.parse([l]).sql;if(!d||!d.trim())return;let m=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(m),s=[];};for(let l of r)l.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(l);a();}dropTable(t,e=false){let r=new Ot(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new Te(t,[new Ct(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new me(t),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||Bt(t,e.join("_")),n=new Dt(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new At(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new ke(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??ee(t,o.join("_")),s=new k("unique",{columns:o,constraintName:n}),a=new Te(t,[new ue(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=F(t,e,r),n=new ce(o),s=new Te(t,[n]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropUnique(t,e,r){let o=Array.isArray(e)?ee(t,e.join("_")):ee(t,e),n=r?.constraintName??o,s=new ce(n),a=new Te(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new Fe,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new k(...e),o=new Te(t,[new ue(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new ce(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAstInstance(t){return new b(t,this.sqlType)}};var Qt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels);}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 m of d)m.type==="belongsTo"&&m.model().table===n.table&&a.push(`fk.${l.table}.${m.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(m=>m.databaseName===n.column);if(d){d.isPrimary&&a.push(`pk.${n.table}`);let m=l.getRelations();for(let p of m)p.columnName===d.columnName&&a.push(`fk.${n.table}.${p.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let 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(m=>m.table===a&&m.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){return this.sql.getDbType()==="sqlite"?[]:t.relation.name?this.sql.alterTable(t.table,e=>{e.dropConstraint(t.relation.name);}):[]}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,e=>{e.dropPrimaryKey();})}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);})}generateDropColumnSql(t){return this.sql.alterTable(t.table,e=>{e.dropColumn(t.column);})}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var kt=class{constructor(t){this.sql=t,this.models=Object.values(this.sql.registeredModels),this.dropResolver=new Qt(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.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);}});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.alterTable(o.table,s=>{s.dropConstraint(o.name);});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 re(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||Me(o.table,o.columns[0]),l=this.sql.alterTable(o.table,d=>{let m=a||Me(o.table,o.columns[0]);d.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:m});});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(m=>m.columnName===l)?.databaseName||l),a=this.sql.alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});});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=w(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=w(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,F(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=w(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||Me(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.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});})}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.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.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});})}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 re(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=w(t.relation.manyToManyOptions.throughModel),r=w(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=w(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),y=c.primaryKey,g=c.getColumns().find(S=>S.columnName===y);if(g)n=g.databaseName;else {let S=c?.databaseCaseConvention||"preserve";n=I(y,S);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let y=c.getColumns(),h=y.find(g=>g.columnName===n);if(h)n=h.databaseName;else {let g=c.primaryKey||"id",S=y.find(_=>_.columnName===g);if(S)n=S.databaseName;else {let _=c?.databaseCaseConvention||"preserve";n=I(n||g,_);}}}else {let y=c.primaryKey||"id",g=c.getColumns().find(S=>S.columnName===y);if(g)n=g.databaseName;else {let S=c?.databaseCaseConvention||"preserve";n=I(y,S);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,d=a.find(c=>c.columnName===l);if(d)l=d.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=I(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(y=>y.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let y=s?.databaseCaseConvention||"preserve";l=I(t.relation.foreignKey,y);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,y=w(c),h=a.find(g=>g.columnName===y);if(h)l=h.databaseName;else {let g=s?.databaseCaseConvention||"preserve";l=I(y,g);}}let m=t.relation.onDelete?.toLowerCase(),p=t.relation.onUpdate?.toLowerCase();return this.sql.alterTable(t.table,c=>{let y=o||F(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:y,onDelete:m,onUpdate:p});})}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 md(i){return i.replace(/\s+/g," ").trim()}function pd(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function Ce(i,t){let e=md(t.toLowerCase()),r=pd(e);switch(i){case "sqlite":{let o=[{test:n=>n.includes("int"),normalized:"integer"},{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":return "integer";case "tinyint":return "tinyint";case "smallint":return "smallint";case "mediumint":return "mediumint";case "bigint":return "bigint";case "float":return "float";case "double":case "double precision":return "double";case "real":return "double";case "decimal":case "numeric":return "numeric";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 "character varying":return "varchar";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":return "integer";case "mediumint":return "integer";case "bigint":case "int8":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}}default:return r}}var Ft=class i{constructor(t){this.emptyStatements=[/alter table ".*"$/];this.sql=t,this.models=Object.values(this.sql.registeredModels),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(d=>d?.type!==void 0&&d?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let m of n.indexes)o.indexes.map(p=>p.name).includes(m.name)||e.data.indexesToAdd.push({table:r.table,index:m.name});let d=r.getUniques?.()||[];for(let m of d)e.data.uniquesToAdd.push({table:r.table,name:m.name||"mandatory",columns:m.columns});for(let m of n.relations){if(m.type!=="belongsTo")continue;let p=w(m.constraintName);o.foreignKeys.find(y=>y.name===p)||e.data.relationsToAdd.push({table:r.table,relation:m,onDelete:m.onDelete,onUpdate:m.onUpdate});}return}for(let d of n.columns)o.columns.some(p=>p.name===d.databaseName||p.name===d.columnName)||e.data.columnsToAdd.push({table:r.table,column:d});for(let d of o.columns)n.columns.some(p=>p.databaseName===d.name||p.columnName===d.name)||e.data.columnsToDrop.push({table:r.table,column:d.name});for(let d of n.indexes)o.indexes.map(m=>m.name).includes(d.name)||e.data.indexesToAdd.push({table:r.table,index:d.name});let s=r.getUniques?.()||[];for(let d of s)o.indexes.some(p=>p.name===d.name&&p.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:d.name||"mandatory",columns:d.columns});for(let d of o.indexes)d.isUnique||n.indexes.map(p=>p.name).includes(d.name)||e.data.indexesToDrop.push({table:r.table,index:d.name});for(let d of o.indexes){if(!d.isUnique)continue;(r.getUniques?.()||[]).map(p=>p.name).includes(d.name)||e.data.uniquesToDrop.push({table:r.table,name:d.name});}for(let d of n.columns){let m=o.columns.find(y=>y.name===d.databaseName||y.name===d.columnName);if(!m)continue;let p=!e.areColumnsEqual(m,d,o.indexes),c=e.getDefaultChange({table:r.table,dbColumns:m,modelColumn:d});(p||c)&&e.data.columnsToModify.push({table:r.table,dbColumns:m,modelColumn:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;if(d.type==="manyToMany"&&d.manyToManyOptions){let c=w(d.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:c,relation:{type:"belongsTo",model:()=>r,columnName:w(d.manyToManyOptions.leftForeignKey),foreignKey:d.manyToManyOptions.leftForeignKey,constraintName:d.constraintName?w(d.constraintName):F(c,w(d.manyToManyOptions.leftForeignKey||Ne(r.table)),r.table),onDelete:d.onDelete,onUpdate:d.onUpdate},onDelete:d.onDelete,onUpdate:d.onUpdate});continue}let m=w(d.constraintName);if(m&&o.foreignKeys.some(c=>c.name===m))continue;o.foreignKeys.find(c=>e.relationMatchesDbRelation(r,d,c))||e.data.relationsToAdd.push({table:r.table,relation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let a=new Set(n.relations.filter(d=>d.type==="belongsTo").map(d=>{let m=w(d.foreignKey)||d.columnName,c=r.getColumns().find(y=>y.columnName===m)?.databaseName||m;return w(d.constraintName)||F(r.table,c,d.model().table)}));for(let d of o.foreignKeys){if(d.name&&a.has(d.name))continue;n.relations.find(p=>p.type!=="belongsTo"&&p.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,p,d))||e.data.relationsToDrop.push({table:r.table,relation:d});}for(let d of n.relations){if(d.type!=="belongsTo"&&d.type!=="manyToMany")continue;let m=o.foreignKeys.find(p=>e.relationMatchesDbRelation(r,d,p));m&&!e.areRelationsEqual(m,d)&&e.data.relationsToModify.push({table:r.table,dbRelation:m,modelRelation:d,onDelete:d.onDelete,onUpdate:d.onUpdate});}let l=r.primaryKey;if(l&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[l]}),o.primaryKey&&!l&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),l&&o.primaryKey){let d=r.getColumns().find(m=>m.columnName===l);d&&!e.arePrimaryKeysEqual(o.primaryKey,d)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:l});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat()}getSqlStatementsByPhase(){let t=new kt(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=Ce(n,t.dataType),a=typeof e.type=="string"?Ce(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")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,m=t.isNullable;o=o&&d===m;}return o}areRelationsEqual(t,e){let r=w(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let d=e.model(),m=d.primaryKey||"id",p=d.getColumns().find(h=>h.columnName===m),c=d.table,y=p?.databaseName||m;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===y;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let d=w(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 g=n.model();g&&g.table&&(o=g);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?w(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=w(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),m=(n.type||"belongsTo")==="belongsTo"?w(n.foreignKey):n.columnName,p=l.find(g=>g.columnName===m);p&&(m=p.databaseName);let c=o.primaryKey||"id",h=o.getColumns().find(g=>g.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===m&&r.referencedColumns.length===1&&r.referencedColumns[0]===h}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&n}getDefaultChange(t){let e=this.sql.getDbType(),r=Ce(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Ce(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||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 n=t.modelColumn.constraints?.default!==void 0,s=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0;if(n&&!s)return "set";if(!n&&s)return "drop";if(n&&s){let a=String(t.dbColumns.defaultValue),l=String(t.modelColumn.constraints?.default),d=this.normalizeDefaultValue(e,r,a),m=this.normalizeDefaultValue(e,o||r,l);return d!==m?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o)?"current_timestamp":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=w(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find(x=>x.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",d=a.primaryKey||"id",m=s.getColumns().find(x=>x.columnName===l),p=a.getColumns().find(x=>x.columnName===d);if(!m||!p)continue;let c=w(o.manyToManyOptions.leftForeignKey)||l,y=w(o.manyToManyOptions.rightForeignKey)||d,h=await this.sql.getTableSchema(n);if(!h.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(m,c),this.clonePkAsColumn(p,y)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:y,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let g=this.clonePkAsColumn(m,c),S=this.clonePkAsColumn(p,y),_=h.columns.find(x=>x.name===c),B=h.columns.find(x=>x.name===y),H=_?this.areColumnsEqual(_,g,h.indexes):false,X=B?this.areColumnsEqual(B,S,h.indexes):false;for(let x of h.foreignKeys){let he=x.referencedTable===s.table,fr=x.referencedTable===a.table;if(!he&&!fr)continue;let Bl=he?c:y,Ve=x.columns[0];Ve&&Ve!==Bl&&(this.data.relationsToDrop.push({table:n,relation:x}),Ve!==c&&Ve!==y&&this.data.columnsToDrop.push({table:n,column:Ve}));}let W={};H||(W[g.databaseName]=g),X||(W[S.databaseName]=W[S.databaseName]||S);for(let x of Object.keys(W))this.data.columnsToAdd.push({table:n,column:W[x]});let ie=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),C=this.buildBelongsToRelation(n,o.model,y,d,void 0,o.onDelete,o.onUpdate),$e=h.foreignKeys.find(x=>x.referencedTable===s.table&&x.columns.length===1&&x.columns[0]===c),ct=h.foreignKeys.find(x=>x.referencedTable===a.table&&x.columns.length===1&&x.columns[0]===y);if(!$e){let x=h.foreignKeys.find(he=>he.referencedTable===s.table);x&&this.data.relationsToDrop.push({table:n,relation:x}),this.data.relationsToAdd.push(ie);}if(!ct){let x=h.foreignKeys.find(he=>he.referencedTable===a.table);x&&this.data.relationsToDrop.push({table:n,relation:x}),this.data.relationsToAdd.push(C);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,m=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,p=w(a.constraintName)||F(o.table,m,a.model().table);s.add(p);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(g=>g.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(S=>S.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(S=>S.columnName===l)?.databaseName||l;let d=o.table,m=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let g=o.relation.model();d=g.table;let S=g.primaryKey||"id";m=g.getColumns().find(B=>B.columnName===S)?.databaseName||S;}let p=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(g=>{if(g.columns.length!==1||g.referencedColumns.length!==1)return false;let S=p.has(g.columns[0]),_=g.referencedTable===d,B=g.referencedColumns[0]===m;return S&&_&&B}),y=w(o.relation.constraintName)||F(o.table,l,d),h=e.get(o.table)||new Set;if(c||y&&h.has(y))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let g=w(o.relation.manyToManyOptions.throughModel),S=w(o.relation.manyToManyOptions.leftForeignKey),_=w(o.relation.manyToManyOptions.rightForeignKey),B=o.table===g&&o.relation.columnName===S&&o.relation.model().table===s?.table,H=o.table===g&&o.relation.columnName===_&&o.relation.model().table!==s?.table,X=await this.sql.getTableSchema(g),W=X.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===S&&C.referencedTable===(s?.table||"")),ie=X.foreignKeys.some(C=>C.columns.length===1&&C.columns[0]===_&&C.referencedTable===o.relation.model().table);if(B&&W||H&&ie)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 p=a.find(S=>S.columnName===d.foreignKey)?.databaseName||d.foreignKey,c=d.model(),y=c.primaryKey||"id",g=c.getColumns().find(S=>S.columnName===y)?.databaseName||y;return o.relation.columns.length===1&&o.relation.columns[0]===p&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===g})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){return {columnName:e,databaseName:e,isPrimary:false,type:t.type,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?w(n):F(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 pe=class extends T{constructor(e,r=false){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e;}};var $=class extends T{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var K=class extends T{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 oe=class extends T{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 z=class extends T{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 O=class extends T{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 Ze=class extends T{constructor(e,r="and"){super("where");this.canKeywordBeSeenMultipleTimes=false;this.folder="where";this.file="where_group";this.nodes=e,this.chainsWith=` ${r}`;}};var J=class extends O{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 we=class extends T{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 L=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Lt=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);});}},fl=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool("sqlite");if(o)return new Promise((d,m)=>{n.run(i,t,function(p){p&&m(p),d(this.changes);});});if(r.mode==="fetch")return new Promise((d,m)=>{n.all(i,t,(p,c)=>{p&&m(p),(!c||!c.length)&&d([]),d(c);});});let s=r?.typeofModel;if(!s)return new Promise((d,m)=>{n.run(i,t,function(p){p?m(new Error(p.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((p,c)=>{n.run(i,t,function(y){if(y)return c(y);let h=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){p(h);return}let g=h?.[a]||this.lastID;if(!g)return c(new u("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let S=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(S,[g],(_,B)=>{if(_)return c(_);p(B);});});});if(!Array.isArray(r.models))throw new u("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let d=r.models,m=[];return new Promise(async(p,c)=>{try{let y=d.map(async h=>{let g=new f(s),{columns:S,values:_}=await g.prepareColumns(Object.keys(h),Object.values(h),"insert"),B=Object.fromEntries(S.map((ie,C)=>[ie,_[C]])),H=new b(s,e.getDbType()),{sql:X,bindings:W}=H.parse([new K(new $(s.table),[B])]);return new Promise((ie,C)=>{n.run(X,W,function($e){if($e)return C($e);let ct=h[a]||this.lastID;if(!a){ie(h);return}if(!ct)return C(new u("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let x=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(x,[ct],(he,fr)=>{if(he)return C(he);ie(fr);});});})});m=await Promise.all(y),p(m);}catch(y){c(y);}})}return new Promise((d,m)=>{n.run(i,t,function(p){p?m(new Error(p.message)):d(this.changes);});})};var j=async(i,t,e,r="raw",o)=>{let n=e.type;switch(o?.shouldNotLog||He(i,e.logs,t),n){case "mysql":case "mariadb":let s=e.sqlConnection??e.getPool("mysql"),[a]=await as(()=>s.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="affectedRows"?a.affectedRows:a;case "postgres":case "cockroachdb":let l=e.sqlConnection??e.getPool("postgres"),d=await as(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?d.rows:d.rowCount;case "sqlite":let m=await as(()=>fl(i,t,e,{typeofModel:o?.sqlLiteOptions?.typeofModel,mode:o?.sqlLiteOptions?.mode||"fetch",models:o?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs);return r==="raw"?Array.isArray(m)?m:[m]:m;default:throw new u("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${n}`)}},jt=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool("mysql"),a=e.sqlConnection??await s.getConnection(),l=new PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),m=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),p=0,c=false,y=false,h=()=>{try{a.release();}catch{}};return m.on("data",g=>{if(o.onData){p++,Promise.resolve(o.onData(l,g)).then(()=>{p--,c&&p===0&&!y&&(h(),l.end());}).catch(S=>{y=true,h(),l.destroy(S);});return}l.write(g);}),m.on("end",()=>{c=true,p===0&&!y&&(h(),l.end());}),m.on("error",g=>{y=true,h(),l.destroy(g);}),l.on("close",()=>{h();}),l}case "cockroachdb":case "postgres":{let s=e.sqlConnection??await e.getPool("postgres").connect(),a=await import('pg-query-stream').catch(()=>{throw new L("pg-query-stream")}),l=new PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),d=new a.default(i,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),m=s.query(d),p=0,c=false,y=false,h=g=>{try{s.release(g);}catch{}};return m.on("data",g=>{if(o.onData){p++,Promise.resolve(o.onData(l,g)).then(()=>{p--,c&&p===0&&!y&&(h(),l.end());}).catch(S=>{y=true,h(S),l.destroy(S);});return}l.write(g);}),m.on("end",()=>{c=true,p===0&&!y&&(h(),l.end());}),m.on("error",g=>{y=true,h(g),l.destroy(g);}),l}case "sqlite":{let s=e.sqlConnection??e.getPool("sqlite");return new Lt(s,i,t,{onData:o.onData})}default:throw new u("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function as(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++,Rs(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}var E=(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 Y=class extends T{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 Xe=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Wt(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 u("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Ut(i,t,e){return {total:e,perPage:t,currentPage:i,firstPage:1,isEmpty:e===0,lastPage:Math.max(1,Math.ceil(e/t)),hasMorePages:i<Math.max(1,Math.ceil(e/t)),hasPages:e>t}}function gl(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var je=i=>typeof i=="number"?i:parseFloat(i);var xe=class extends T{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 Vt=class extends T{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var Ht=class extends T{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var G=class extends T{constructor(e,r,o,n="inner",s,a=false){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;}};var et=class extends T{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 Yt=class extends T{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var zt=class extends T{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var tt=class extends T{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 Jt=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 et(e));}),this}groupByRaw(t){return this.groupByNodes.push(new et(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new tt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new tt(t,"asc",true)),this}limit(t){return typeof t!="number"&&N.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new Yt(t),this}offset(t){return typeof t!="number"&&N.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new zt(t),this}};var Gt=class extends Jt{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new G(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new G(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new G(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new G(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new G(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new G(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,n,s),this}join(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"inner",{operator:s||"="})),this}leftJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"left",{operator:s||"="})),this}rightJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"right",{operator:s||"="})),this}fullJoin(t,e,r,o){let n=r,s=o;if(!n){if(!this.model.primaryKey)throw new u("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");n=`${this.model.table}.${this.model.primaryKey}`;}return this.joinNodes.push(new G(typeof t=="string"?t:t.table,e,n,"full",{operator:s||"="})),this}};var Zt=class extends Gt{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.modelAnnotatedColumns=[];this.dbType=r.getDbType(),this.fromNode=new $(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],e.map(o=>I(o,this.model.databaseCaseConvention)).forEach(o=>{this.selectNodes.push(new Y(o));}),this}selectRaw(e){return this.selectNodes.push(new Y(e,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new $(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes.push(new Y(s,a,n)),this.modelAnnotatedColumns.push(a),this}from(e){return this.fromNode=new $(e),this}table(e){return this.fromNode=new $(e),this}distinct(){return this.distinctNode=new Vt,this}distinctOn(...e){return this.distinctOnNode=new Ht(e),this}};var Xt=class extends Zt{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 R&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||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 R&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 R&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof R||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof R)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new O(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 O(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new O(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 O(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new O(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 O(e,"and",false,"in",r)),this):(this.whereNodes.push(new O("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new O(e,"or",false,"in",r)),this):(this.whereNodes.push(new O("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 O(e,"and",true,"in",r)),this):(this.whereNodes.push(new O("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new O(e,"or",true,"in",r)),this):(this.whereNodes.push(new O("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new O(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new O(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new O(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new O(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 O(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 O(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new O(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new O(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new O(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof R?e:new R(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new we("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new O(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new O(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 xe(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 xe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new xe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new xe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof R)return e;let r=new R(this.model,this.sqlDataSource);return e(r),r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new we(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new we(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new R(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ze(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new R(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Ze(r.whereNodes,"or");return this.whereNodes.push(o),this}};var er=class extends Xt{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new J(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new J(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new J(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new J(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new J(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new J(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new J(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new J(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new J(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new J(t,"or",false,"raw",e)),this}};var R=class i extends er{constructor(e,r=ne.getInstance()){super(e,r);this.isNestedCondition=false;this.mustRemoveAnnotations=false;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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);}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return j(e,r,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}})}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 first(){return this.one()}async oneOrFail(){let e=await this.one();if(!e)throw new u("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async firstOrFail(){return this.oneOrFail()}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return await jt(r,o,this.sqlDataSource,e,{onData:(s,a)=>{s.write(a);}})}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:gl(e,a),data:s},{key:r.discriminator,value:d}]}selectSubQuery(e,r){if(typeof e=="function"){let o=new i(this.model,this.sqlDataSource);return e(o),this.selectNodes.push(new Y(o.extractQueryNodes(),r)),this}return this.selectNodes.push(new Y(e.extractQueryNodes(),r)),this}lockForUpdate(e={}){return this.lockQueryNodes.push(new Ge("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new Ge("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new De(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new De(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new De(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new De(o,true)),this}async increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}async decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.annotate("count",e,"total");let r=await this.one();return r?je(r.total):0}async getMax(e){this.clearForFunctions(),this.annotate("max",e,"total");let r=await this.one();return r?je(r.total):0}async getMin(e){this.clearForFunctions(),this.annotate("min",e,"total");let r=await this.one();return r?je(r.total):0}async getAvg(e){this.clearForFunctions(),this.annotate("avg",e,"total");let r=await this.one();return r?je(r.total):0}async getSum(e){this.clearForFunctions(),this.annotate("sum",e,"total");let r=await this.one();return r?je(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&N.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),[n,s]=await Promise.all([this.limit(r).offset((e-1)*r).many(),o.getCount("*")]);return {paginationMetadata:Ut(e,r,s),data:n}}from(e,r){if(typeof e=="function"){if(!r)throw new u("QueryBuilder::from","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource);e(o);let n=o.extractQueryNodes();return this.fromNode=new $(n,r),this}return this.fromNode=new $(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 Le("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 Le("recursive",e,n)),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new u("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 Le("materialized",e,n)),this}async insert(e,r){let{columns:o,values:n}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),s=Object.fromEntries(o.map((m,p)=>[m,n[p]]));this.insertNode=new K(this.fromNode,[s],r);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),d=await j(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});return Array.isArray(d)&&d.length?d[0]:d}async insertMany(e,r){if(!e.length)return [];let o=await Promise.all(e.map(async a=>{let{columns:l,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(a),Object.values(a),"insert");return Object.fromEntries(l.map((m,p)=>[m,d[p]]))}));this.insertNode=new K(this.fromNode,o,r);let{sql:n,bindings:s}=this.astParser.parse([this.insertNode]);return j(n,s,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:o}})}async upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(a.map((y,h)=>[y,l[h]])),{sql:m,bindings:p}=this.astParser.parse([new K(new $(this.model.table),[d],void 0,true),new oe(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),c=await j(m,p,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(c)?c:[c]}async upsertMany(e,r,o,n={updateOnConflict:true}){let s=[];await Promise.all(o.map(async m=>{let{columns:p,values:c}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert"),y=Object.fromEntries(p.map((h,g)=>[h,c[g]]));s.push(y);}));let{sql:a,bindings:l}=this.astParser.parse([new K(new $(this.model.table),s,void 0,true),new oe(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await j(a,l,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(d)?d:[d]}async update(e){let r=Object.keys(e),o=Object.values(e),{columns:n,values:s}=await this.interpreterUtils.prepareColumns(r,o,"update");this.updateNode=new z(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return j(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async truncate(){this.truncateNode=new me(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]);await j(e,r,this.sqlDataSource,"raw");}async delete(){this.deleteNode=new pe(this.fromNode);let{sql:e,bindings:r}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]);return j(e,r,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}async softDelete(e={}){let{column:r="deletedAt",value:o=ae()}=e||{},{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new z(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]);return j(a,l,this.sqlDataSource,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})}toQuery(){let{sql:e,bindings:r}=this.unWrap();return Ds(e,r)}unWrap(){this.selectNodes.length||(this.selectNodes=[new Y("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes()),o=yt(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.modelAnnotatedColumns=v(this.modelAnnotatedColumns),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.mustRemoveAnnotations=this.mustRemoveAnnotations,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 Y("*")]),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 E(this.many.bind(this),e)();return {data:o,time:Number(r)}}async oneWithPerformance(e="millis"){let[r,o]=await E(this.one.bind(this),e)();return {data:o,time:Number(r)}}async firstWithPerformance(e="millis"){return this.oneWithPerformance(e)}async firstOrFailWithPerformance(e="millis"){return this.oneOrFailWithPerformance(e)}async paginateWithPerformance(e,r,o="millis"){let[n,s]=await E(this.paginate.bind(this,e,r),o)();return {data:s,time:Number(n)}}async paginateWithCursorWithPerformance(e,r,o,n="millis"){let[s,a]=await E(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async oneOrFailWithPerformance(e="millis"){let[r,o]=await E(this.oneOrFail.bind(this),e)();return {data:o,time:Number(r)}}async existsWithPerformance(e="millis"){let[r,o]=await E(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await E(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r="millis"){let[o,n]=await E(this.update.bind(this,e),r)();return {data:n,time:Number(o)}}async insertWithPerformance(e,r="millis"){let[o,n]=await E(this.insert.bind(this,e),r)();return {data:n,time:Number(o)}}async insertManyWithPerformance(e,r="millis"){let[o,n]=await E(this.insertMany.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await E(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async deleteWithPerformance(e="millis"){let[r,o]=await E(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await E(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var We=class i extends R{constructor(e,r){super(e,r);this.performance={many:this.manyWithPerformance.bind(this),one:this.oneWithPerformance.bind(this),oneOrFail:this.oneOrFailWithPerformance.bind(this),first:this.firstWithPerformance.bind(this),firstOrFail:this.firstOrFailWithPerformance.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 Xe(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 first(e){return this.one(e)}async oneOrFail(e){let r=await this.one(e);if(!r)throw new u(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async firstOrFail(e){return this.oneOrFail(e)}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 le(o,this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);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}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();return await jt(r,o,this.sqlDataSource,e,{onData:async(s,a)=>{let l=this.addAdditionalColumnsToModel(a,this.model),d=await le([l],this.model,this.modelSelectedColumns,this.modelAnnotatedColumns,this.mustRemoveAnnotations);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),s.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new u(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}async insert(...e){return this.model.insert(...e)}async insertMany(...e){return this.model.insertMany(...e)}async update(e,r={}){return r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),super.update(e)}async softDelete(e={}){let{ignoreBeforeUpdateHook:r=false}=e||{};return !r&&await this.model.beforeUpdate?.(this),super.softDelete(e)}async delete(e={}){return e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),super.delete()}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("count",e,"total");let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("max",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("min",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("avg",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.annotate("sum",e,"total");let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.$annotations.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),[s,a]=await Promise.all([this.limit(r).offset((e-1)*r).many({ignoreHooks:o.ignoreHooks?["beforeFetch","afterFetch"]:[]}),n.getCount("*",{ignoreHooks:o.ignoreHooks})]);return {paginationMetadata:Ut(e,r,a),data:s}}select(...e){return this.modelSelectedColumns=[...this.modelSelectedColumns,...e],this.selectNodes=this.selectNodes.concat(e.map(r=>new Y(r))),this}annotate(e,r,o){let n,s,a;return o?(n=e,s=r,a=o):(n=void 0,s=e,a=r),this.selectNodes=this.selectNodes.concat(new Y(s,a,n)),this.modelAnnotatedColumns.push(a),this}removeAnnotations(){return this.mustRemoveAnnotations=true,this.modelAnnotatedColumns=[],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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.whereExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.orWhereExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.whereNotExists(m),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 m=this.getRelatedModelsQueryForRelation(d,l,[]);return m.clearWhere(),m.clearSelect(),m.selectRaw("1"),a?.(m),this.applyHavingRelatedFilter(m,l,s,n),this.orWhereNotExists(m),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 u(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let y=c[e.foreignKey];y&&n.set(String(y),c);}),r.forEach(c=>{let y=c[this.model.primaryKey];if(!y){c[e.columnName]=null;return}let h=n.get(String(y));c[e.columnName]=h||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new u(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let y=c[e.model.primaryKey];y&&s.set(String(y),c);}),r.forEach(c=>{let y=c[e.foreignKey];if(!y){c[e.columnName]=null;return}let h=s.get(String(y));c[e.columnName]=h||null;});break;case "hasMany":if(!this.model.primaryKey)throw new u(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let y=c[e.foreignKey];if(!y)return;let h=String(y);a.has(h)||a.set(h,[]),a.get(h).push(c);}),r.forEach(c=>{let y=c[this.model.primaryKey];if(!y){c[e.columnName]=[];return}let h=a.get(String(y))||[];c[e.columnName]=h;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new u(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,d=new Map,m=l.leftForeignKey,p=this.modelColumnsMap.get(m)||this.modelColumnsDatabaseNames.get(m)||I(m,this.model.modelCaseConvention);o.forEach(c=>{let y=c.$annotations||{},h=y[p];if(h==null)return;let g=String(h);d.has(g)||d.set(g,[]),this.modelAnnotatedColumns.includes(p)||(delete y[p],Object.keys(y).length||delete c.$annotations),d.get(g).push(c);}),r.forEach(c=>{let y=c[this.model.primaryKey];if(!y){c[e.columnName]=[];return}let h=d.get(String(y))||[];c[e.columnName]=h;});break;default:throw new u(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=ge.randomBytes(6).toString("hex"),d=`${r.model.table}_cte_${l}`,m=e.orderByNodes.map(C=>C.isRawValue?C.column:`${this.interpreterUtils.formatStringColumn(this.dbType,C.column)} ${C.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let p=e.with(d,C=>C.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${m}) as rn_${l}`).whereIn(r.foreignKey,n));s&&p.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&p.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(C=>Sr(C,d,e.model.table));return p.select(...c).from(d);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new u(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let y=r;if(!o.length)return e;let h=e.limitNode?.limit,g=e.offsetNode?.offset,S=e.modelSelectedColumns.length?e.modelSelectedColumns.map(C=>C.includes(".")?C:`${r.model.table}.${C}`):[`${r.model.table}.*`];if(!h&&!g)return e.select(...S).annotate(`${y.throughModel}.${y.leftForeignKey}`,y.leftForeignKey).leftJoin(y.throughModel,`${y.relatedModel}.${y.model.primaryKey}`,`${y.throughModel}.${y.rightForeignKey}`).whereIn(`${y.throughModel}.${y.leftForeignKey}`,n);let _=ge.randomBytes(6).toString("hex"),B=`${r.model.table}_cte_${_}`,H=e.orderByNodes.map(C=>{if(C.isRawValue)return C.column;let $e=C.column.includes(".")?C.column:`${r.model.table}.${C.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,$e)} ${C.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let X=`${ge.randomBytes(6).toString("hex")}_left_foreign_key`,W=e.with(B,C=>C.select(...S).annotate(`${y.throughModel}.${y.leftForeignKey}`,X).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${y.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,y.leftForeignKey)} ORDER BY ${H}) as rn_${_}`).leftJoin(y.throughModel,`${y.relatedModel}.${y.model.primaryKey}`,`${y.throughModel}.${y.rightForeignKey}`).whereIn(`${y.throughModel}.${y.leftForeignKey}`,n));h&&W.whereRaw(`rn_${_} <= ${h+(g||0)}`),g&&W.whereRaw(`rn_${_} > ${g}`);let ie=S.map(C=>Sr(C,B,e.model.table));return W.select(...ie).annotate(`${B}.${X}`,y.leftForeignKey).from(B);default:throw new u(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new u(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 u(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new u(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 u(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let d=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),m=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${d} = ${m}`),o&&typeof n=="number"&&e.groupByRaw(d).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new u(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}`),m=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${d} = ${m}`),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 u(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(y=>!y.isRawValue&&y.table===d.throughModel&&y.type==="left")||e.leftJoin(d.throughModel,`${d.relatedModel}.${r.model.primaryKey}`,`${d.throughModel}.${d.rightForeignKey}`);let p=a.formatStringColumn(l,`${d.throughModel}.${d.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${p} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(p).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new u(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e,r){let o={},n={};return Object.entries(e).forEach(([s,a])=>{if(s==="$annotations"||this.modelColumnsDatabaseNames.get(s)){o[s]=a;return}n[I(s,r.modelCaseConvention)]=a;}),o.$annotations=n,o}async manyWithPerformance(e={},r="millis"){let[o,n]=await E(this.many.bind(this,e),r)();return {data:n,time:Number(o)}}async oneWithPerformance(e={},r="millis"){let[o,n]=await E(this.one.bind(this,e),r)();return {data:n,time:Number(o)}}async oneOrFailWithPerformance(e={},r="millis"){let[o,n]=await E(this.oneOrFail.bind(this,e),r)();return {data:n,time:Number(o)}}async firstOrFailWithPerformance(e={},r="millis"){return this.oneOrFailWithPerformance(e,r)}async firstWithPerformance(e={},r="millis"){return this.oneWithPerformance(e,r)}async paginateWithPerformance(e,r,o,n="millis"){let{ignoreHooks:s=false}=o||{},[a,l]=await E(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 E(this.paginateWithCursor.bind(this,e,r,o),n)();return {data:a,time:Number(s)}}async existsWithPerformance(e="millis"){let[r,o]=await E(this.exists.bind(this),e)();return {data:o,time:Number(r)}}async pluckWithPerformance(e,r="millis"){let[o,n]=await E(this.pluck.bind(this,e),r)();return {data:n,time:Number(o)}}async softDeleteWithPerformance(e={},r="millis"){let[o,n]=await E(this.softDelete.bind(this,e),r)();return {data:n,time:Number(o)}}async updateWithPerformance(e,r={},o="millis"){let[n,s]=await E(this.update.bind(this,e,r),o)();return {data:s,time:Number(n)}}async deleteWithPerformance(e="millis"){let[r,o]=await E(this.delete.bind(this),e)();return {data:o,time:Number(r)}}async truncateWithPerformance(e="millis"){let[r,o]=await E(this.truncate.bind(this),e)();return {data:o,time:Number(r)}}};var tr=class extends We{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new K(this.fromNode,[o],r?.returning),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new K(this.fromNode,o,r?.returning),this}update(...t){let[e]=t;return this.updateNode=new z(this.fromNode,Object.keys(e),Object.values(e)),this}delete(...t){let[e]=t;return e?.ignoreBeforeDeleteHook||this.model.beforeDelete?.(this),this.deleteNode=new pe(this.fromNode),this}truncate(){return this.truncateNode=new me(this.fromNode),this}softDelete(...t){let[e]=t,{column:r="deletedAt",value:o=ae()}=e||{};return this.updateNode=new z(this.fromNode,[r],[o]),this}};function Tl(i){let t=i.name,e=I(t,"snake");return dd(e)}function bl(){return {}}var rt=class{constructor(t,e){this.model=t,this.modelInstance=bl(),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);}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&&Object.entries(t.where).forEach(([r,o])=>{if(Array.isArray(o)){e.whereIn(r,o);return}e.where(r,o);}),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 u(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new u(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}async insert(t,e={}){!e.ignoreHooks&&await this.model.beforeInsert?.(t);let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),n={};r.forEach((p,c)=>{let y=o[c];n[p]=y,t[p]??(t[p]=y);});let{sql:s,bindings:a}=this.astParser.parse([new K(new $(this.model.table),[n],e.returning)]),l=await j(s,a,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(l,[t],"one",e.returning);let d=l[0];return d?(await this.model.afterFetch?.([d]),await le([d],this.model)):t}async insertMany(t,e={}){let r=[];await this.model.beforeInsertMany?.(t);for(let d of t){let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),c={};m.forEach((y,h)=>{let g=p[h];c[y]=g,d[y]??(d[y]=g);}),r.push(c);}let{sql:o,bindings:n}=this.astParser.parse([new K(new $(this.model.table),r,e.returning)]),s=await j(o,n,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(s,t,"many",e.returning)||[];let a=s;return a.length?(await this.model.afterFetch?.(a),await le(a,this.model)||[]):[]}async upsertMany(t,e,r,o={updateOnConflict:true}){let n=[];await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async d=>{let{columns:m,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(d),Object.values(d),"insert"),c=Object.fromEntries(m.map((y,h)=>[y,p[h]]));n.push(c);}));let{sql:s,bindings:a}=this.astParser.parse([new K(new $(this.model.table),n,void 0,true),new oe(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",o.returning)]);return await j(s,a,this.sqlDataSource,"raw",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}})}async updateRecord(t,e){let{columns:r,values:o}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"update"),{primaryKey:n}=this.model;if(!n)throw new u(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");r=r.filter(d=>d!==n),o=o.filter(d=>d!==t[n]);let{sql:s,bindings:a}=this.astParser.parse([new z(new $(this.model.table),r,o),new O(n,"and",false,"=",t[n])]);await j(s,a,this.sqlDataSource,"raw");let l=await this.findOneByPrimaryKey(t[this.model.primaryKey],e?.returning??void 0);if(!l)throw new u(this.model.name+"::updateRecord","ROW_NOT_FOUND");return l}async deleteRecord(t){if(!this.model.primaryKey)throw new u(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new O(this.model.primaryKey,"and",false,"=",t[this.model.primaryKey]),{sql:r,bindings:o}=this.astParser.parse([new pe(new $(this.model.table)),e]);await j(r,o,this.sqlDataSource,"raw");}query(){return new We(this.model,this.sqlDataSource)}dryQuery(){return new tr(this.model,this.sqlDataSource)}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await le([a],this.model):null}return await le(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(m=>m[this.model.primaryKey]),l=a.map(m=>`'${m}'`).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}};var ot=class extends R{constructor(t,e){super(t,e);}many(){return this}insert(...t){let[e,r]=t,o=Object.fromEntries(Object.keys(e).map(n=>[n,e[n]]));return this.insertNode=new K(this.fromNode,[o],r),this}insertMany(...t){let[e,r]=t;if(!e.length)return this;let o=e.map(n=>Object.fromEntries(Object.keys(n).map(s=>[s,n[s]])));return this.insertNode=new K(this.fromNode,o,r),this}upsert(...t){let[e,r,o]=t,n=Object.keys(e),s=Object.keys(r);return this.insertNode=new K(new $(this.model.table),[e],void 0,true),this.onDuplicateNode=new oe(this.model.table,s,n,o?.updateOnConflict??true?"update":"ignore",o?.returning),this}upsertMany(...t){let[e,r,o,n]=t,s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new K(new $(this.model.table),s,void 0,true),this.onDuplicateNode=new oe(this.model.table,e,r,n?.updateOnConflict??true?"update":"ignore",n?.returning),this}update(t){return this.updateNode=new z(this.fromNode,Object.keys(t),Object.values(t)),this}delete(){return this.deleteNode=new pe(this.fromNode),this}truncate(){return this.truncateNode=new me(this.fromNode),this}softDelete(t={}){let{column:e="deletedAt",value:r=ae()}=t||{};return this.updateNode=new z(this.fromNode,[e],[r]),this}};var nt=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??ae()});var ye=class{constructor(t){this.options=t;}static async createDriver(t){throw new u("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var rr=class i extends ye{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(e){let r=await import('mongodb').catch(()=>{throw new L("mongodb")});if(!r)throw new L("mongodb");return new i(r,e)}};var or=class i extends ye{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(e){let r=await import('mysql2/promise').catch(()=>{throw new L("mysql2")});if(!r)throw new L("mysql");return new i(r.default,e)}};var nr=class i extends ye{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(e){let r=await import('pg').catch(()=>{throw new L("pg")});if(!r)throw new L("pg");return new i(r.default,e)}};var sr=class i extends ye{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(e){let r=await import('sqlite3').catch(()=>{throw new L("sqlite3")});if(!r)throw new L("sqlite3");return new i(r.default,e)}};var Ie=class{static async getDriver(t,e){switch(t){case "mysql":case "mariadb":return or.createDriver(e);case "postgres":case "cockroachdb":return nr.createDriver(e);case "sqlite":return sr.createDriver(e);case "mongo":return rr.createDriver(e);default:throw new u(`DriverFactory::getDriver Driver ${t} not found, il likely not installed, try running npm install ${t}`,"DRIVER_NOT_FOUND")}}};var hd=async i=>(await Ie.getDriver(i)).client,st=async(i,t)=>{let e=await hd(i);switch(i){case "mariadb":case "mysql":let r=t;return e.createPool({host:r.host,port:r.port,user:r.username,password:r.password,database:r.database,...r?.driverOptions});case "postgres":case "cockroachdb":let s=t,a=e;return new a.Pool({host:s.host,port:s.port,user:s.username,password:s.password,database:s.database,...s?.driverOptions});case "sqlite":let d=e,m=t?.database;return new d.Database(m,d.OPEN_READWRITE|d.OPEN_CREATE,c=>{if(c)throw new u("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});default:throw new u("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var it=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=ge.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.startTransaction(),t)try{await t(e),await e.commit();}catch(r){throw await e.rollback(),r}return e}async startTransaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mysql":case "mariadb":case "postgres":case "cockroachdb":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 "mysql":case "mariadb":t&&await this.sql.rawQuery(t),await this.sql.sqlConnection.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}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new u("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");N.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){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 "mysql":case "mariadb":await this.sql.sqlConnection.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break}}catch(e){throw N.error(e),e}await this.releaseConnection(),this.isActive=false;}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new u("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");N.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}try{if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mysql":case "mariadb":case "postgres":case "cockroachdb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new u("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=!1;return}switch(this.sql.type){case "mysql":case "mariadb":await this.sql.sqlConnection.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;default:throw new u("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw N.error(e),e}await this.releaseConnection(),this.isActive=false;}async releaseConnection(){if(!this.connectionReleased){try{switch(this.sql.type){case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;default:throw new u("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(t){N.error(t);}await this.sql.closeConnection(),this.sql.sqlConnection=null,this.connectionReleased=true;}}getIsolationLevelQuery(){if(!this.isolationLevel)return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new u("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new u("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}};var se=class se extends ve{constructor(e){super(e);this.globalTransaction=null;this.models={};this.ownsPool=false;this.sqlConnection=null;this.sqlType=this.type,this.inputDetails=e||{connectionPolicies:{retry:{maxRetries:0,delay:0}},queryFormatOptions:{language:pt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"}},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:pt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"};}static async connect(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new se(e);if(e?.models){let n=o.sanitizeModelKeys(e?.models||{});Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),se.instance=o,await r?.(o),o}static async connectToSecondarySource(e,r){typeof e=="function"&&(r=e,e=void 0);let o=new se(e);if(e?.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}return o.models=e?.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:o.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1"),se.instance=o,await r?.(o),o}static async useConnection(e,r){let o=new se(e);if(e.models){let n=o.sanitizeModelKeys(e.models);Object.assign(o,n);}o.models=e.models||{},o.sqlPool=await st(o.sqlType,{type:o.sqlType,host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,connectionPolicies:o.inputDetails.connectionPolicies,queryFormatOptions:o.inputDetails.queryFormatOptions,driverOptions:o.inputDetails.driverOptions,logs:o.logs,models:e.models}),o.ownsPool=true,await o.testConnectionQuery("SELECT 1");try{await r(o).then(async()=>{o.isConnected&&await o.closeConnection();});}catch(n){throw o.isConnected&&await o.closeConnection(),n}}static getInstance(){if(!se.instance)throw new u("SqlDataSource::getInstance","CONNECTION_NOT_ESTABLISHED");return se.instance}static query(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new R(nt(e,r),n);return r?.alias&&s.from(e,r.alias),s}static dryQuery(e,r){let o=this.getInstance(),n=o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o,s=new ot(nt(e,r),n);return r?.alias&&s.from(e,r.alias),s}static createTable(...e){return this.getInstance().createTable(...e)}static alterTable(...e){return this.getInstance().alterTable(...e)}static async startGlobalTransaction(e){return this.getInstance().startGlobalTransaction(e)}static async commitGlobalTransaction(){await this.getInstance().commitGlobalTransaction();}static async rollbackGlobalTransaction(){await this.getInstance().rollbackGlobalTransaction();}static async startTransaction(e,r){return this.getInstance().startTransaction(e,r)}static async transaction(e,r){let o=typeof e=="function"?r:e;return this.getInstance().startTransaction(e,o)}static async getTableSchema(e){return this.getInstance().getTableSchema(e)}static async closeConnection(){if(!this.instance){N.warn("Connection already closed");return}await this.instance.closeConnection(),this.instance=null;}static async disconnect(){return this.closeConnection()}static async rawQuery(e,r=[]){let o=this.getInstance();return (o.isInGlobalTransaction&&o.globalTransaction?.isActive?o.globalTransaction.sql:o).rawQuery(e,r)}static rawStatement(e){return this.getInstance().rawStatement(e)}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async clone(e){let r=new se(this.inputDetails);if(r.sqlType==="sqlite"||!!e?.shouldRecreatePool){if(r.sqlPool=await st(r.sqlType,{type:r.sqlType,host:r.host,port:r.port,username:r.username,password:r.password,database:r.database,connectionPolicies:r.inputDetails.connectionPolicies,queryFormatOptions:r.inputDetails.queryFormatOptions,driverOptions:r.inputDetails.driverOptions,logs:r.logs,models:r.models}),r.ownsPool=true,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}if(r.sqlPool=this.sqlPool,r.ownsPool=false,Object.keys(this.models).length){let n=r.sanitizeModelKeys(this.models);Object.assign(r,n);}return r}getDbType(){return this.type}query(e,r){let o=this.isInGlobalTransaction&&this.globalTransaction?.isActive?this.globalTransaction.sql:this,n=new R(nt(e,r),o);return r?.alias&&n.from(e,r.alias),n}dryQuery(e,r){return new ot(nt(e,r),this)}alterTable(...e){let r=new re(this.getDbType());return r.alterTable(...e),r.queryStatements}createTable(...e){let r=new re(this.getDbType());return r.createTable(...e),r.queryStatements[0]||""}async startGlobalTransaction(e){let r=await this.clone();return r.sqlConnection=await r.getConnection(),this.globalTransaction=new it(r,e?.isolationLevel),await this.globalTransaction.startTransaction(),this.globalTransaction}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new u("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async rollbackGlobalTransaction(e){if(!this.globalTransaction){N.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction}),this.globalTransaction=null;}async startTransaction(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 it(n,o?.isolationLevel);if(await s.startTransaction(),typeof e=="function")try{await e(s),await s.commit({throwErrorOnInactiveTransaction:!1});return}catch(a){throw await s.rollback({throwErrorOnInactiveTransaction:false}),a}return s}async transaction(e,r){return this.startTransaction(e,r)}getModelManager(e){if(!this.isConnected)throw new u("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");return this.globalTransaction?.isActive?new rt(e,this.globalTransaction.sql):new rt(e,this)}getPool(e=this.sqlType){if(!this.sqlPool)throw new u("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(e=this.sqlType){if(this.sqlConnection)return this.sqlConnection;if(!this.sqlPool)throw new u("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;default:throw new u("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async closeConnection(){if(!this.isConnected){He("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{N.warn("SqlDataSource::closeConnection - Error while rolling back global transaction");}switch(He("Closing connection",this.logs),this.type){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;default:throw new u("SqlDataSource::closeConnection",`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}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 disconnect(){return this.closeConnection()}async syncSchema(e){if(e=e||{transactional:false},this.sqlType==="sqlite"){N.warn("Syncing schema with SQLite is not supported, skipping...");return}let o=(await Ft.makeDiff(this)).getSqlStatements();if(!o.length){N.info("No new changes detected between database schema and models metadata");return}if(N.info(`Generated ${o.length} SQL statements to sync schema`),!e?.transactional){for(let n of o)await this.rawQuery(n);N.info(`Synced schema with ${o.length} SQL statements`);return}await this.transaction(async n=>{for(let s of o)await n.sql.rawQuery(s);}),N.info(`Synced schema with ${o.length} SQL statements`);}async rawQuery(e,r=[]){if(!this.isConnected)throw new u("SqlDataSource::rawQuery","CONNECTION_NOT_ESTABLISHED");let o=yt(this,e);return j(o,r,this,"raw")}rawStatement(e){return new de(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 Cs(Object.values(this.models))}async getTableInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new bt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(a){if(Ye(this.getDbType(),a))return [];throw a}let s=this.getDbType();return s==="sqlite"?n.map(a=>{let l=String(a.type||"").toLowerCase(),d=Ce(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(),m=Ce(s,d),p=a.is_nullable!==void 0?a.is_nullable:a.IS_NULLABLE!==void 0?a.IS_NULLABLE:void 0,c=typeof p=="string"?p.toLowerCase()!=="no":typeof p=="boolean"?p:a.notnull!==void 0?a.notnull===0:true,y=a.column_default??a.COLUMN_DEFAULT??a.defaultValue??a.dflt_value??null,h=a.char_length!=null?Number(a.char_length):null,g=a.numeric_precision!=null?Number(a.numeric_precision):null,S=a.numeric_scale!=null?Number(a.numeric_scale):null,_=a.timezone!=null?!!a.timezone:typeof a.datetime_precision=="number"?/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase()):/with time zone/.test(String(a.column_type||a.udt_name||"").toLowerCase());return {name:l,dataType:m,isNullable:c,defaultValue:y,length:h,precision:g,scale:S,withTimezone:_}})}async getIndexInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new gt(e)]).sql,n=this.getDbType(),s=[];try{s=await this.rawQuery(o);}catch(l){if(Ye(this.getDbType(),l))return [];throw l}if(n==="mysql"||n==="mariadb"){let l=new Map;for(let d of s){let m=d.Key_name,p=d.Non_unique===0,c=l.get(m)||{name:m,columns:[],isUnique:p};c.columns.push(d.Column_name),l.set(m,c);}return Array.from(l.values())}if(n==="postgres"||n==="cockroachdb"){let l=new Map;for(let d of s){let m=d.index_name,p=!!d.is_unique,c=l.get(m)||{name:m,columns:[],isUnique:p};c.columns.push(d.column_name),l.set(m,c);}return Array.from(l.values())}let a=[];for(let l of s){let d=l.name,m=!!l.unique,c=(await this.rawQuery(`PRAGMA index_info(${d})`)).map(y=>y.name);a.push({name:d,columns:c,isUnique:m});}return a}async getForeignKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new ht(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(Ye(this.getDbType(),l))return [];throw l}if(this.getDbType()==="sqlite"){let l=new Map;for(let d of n){let m=Number(d.id),p=l.get(m)||{name:void 0,columns:[],referencedTable:String(d.table),referencedColumns:[],onDelete:d.on_delete??null,onUpdate:d.on_update??null};p.columns.push(String(d.from)),p.referencedColumns.push(String(d.to)),l.set(m,p);}return Array.from(l.values())}let a=new Map;for(let l of n){let d=String(l.name||""),m=d||`${l.referenced_table}_${l.column_name}`,p=a.get(m)||{name:d||void 0,columns:[],referencedTable:String(l.referenced_table),referencedColumns:[],onDelete:l.on_delete??null,onUpdate:l.on_update??null};p.columns.push(String(l.column_name)),p.referencedColumns.push(String(l.referenced_column)),a.set(m,p);}return Array.from(a.values())}async getPrimaryKeyInfo(e){let o=new b({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.getDbType()).parse([new Tt(e)]).sql,n=[];try{n=await this.rawQuery(o);}catch(l){if(Ye(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 testConnectionQuery(e){await j(e,[],this,"raw",{shouldNotLog:true});}sanitizeModelKeys(e){let r=Object.getOwnPropertyNames(this),o=Object.getOwnPropertyNames(this.constructor),n=[...r,...o];if(Object.keys(e).some(s=>n.includes(s)))throw new u("SqlDataSource::sanitizeModelKeys","DUPLICATE_MODEL_KEYS_WHILE_INSTANTIATING_MODELS",new Error(`Duplicate model keys while instantiating models inside the connection: ${Object.keys(e).filter(s=>n.includes(s)).map(s=>`"${s}"`).join(", ")}`));return e}static get isInGlobalTransaction(){return !!this.instance?.globalTransaction}get isInGlobalTransaction(){return !!this.globalTransaction}get registeredModels(){return this.models}};se.instance=null;var ne=se;var wl=["postgres","cockroachdb"];var at=class at extends Se{static get table(){let t=Object.getOwnPropertyDescriptor(this,"table");return t&&"value"in t?t.value:Tl(this)}static set table(t){Object.defineProperty(this,"table",{value:t,writable:true,enumerable:true,configurable:true});}static get primaryKey(){return Rl(this)}constructor(){super();}static async all(t={}){return await this.dispatchModelManager(t).find({ignoreHooks:t.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static query(t){return this.dispatchModelManager(t).query()}static dryQuery(t){return this.dispatchModelManager(t).dryQuery()}static async first(t){return this.dispatchModelManager(t).query().one({ignoreHooks:t?.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async find(t,e){return await this.dispatchModelManager(e).find(t)}static async findOneOrFail(t,e){return await this.dispatchModelManager(e).findOneOrFail(t)}static async findOne(t,e){return await this.dispatchModelManager(e).findOne(t)}static async findBy(t,e,r={}){return await this.dispatchModelManager(r).find({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneBy(t,e,r={}){return await this.dispatchModelManager(r).findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:{[t]:e}})}static async findOneByPrimaryKey(t,e={}){return await this.dispatchModelManager(e).findOneByPrimaryKey(t)}static async refresh(t,e={}){let r=this,o=r.dispatchModelManager(e),n=r.primaryKey,s=t[n],a=await o.findOneByPrimaryKey(s);return a||null}static async insert(t,e={}){return this.dispatchModelManager(e).insert(t,{ignoreHooks:e.ignoreHooks,returning:e.returning})}static async insertMany(t,e={}){return t.length?this.dispatchModelManager(e).insertMany(t,{ignoreHooks:e.ignoreHooks,returning:e.returning}):[]}static async sync(t,e,r,o,n={}){if(Array.isArray(r)||(r=[r]),!r.length)return;let s=this,l=Wt(s).find(h=>h.columnName===t);if(!l)throw new u(`${s.name}::sync`,"RELATION_NOT_FOUND");if(l.type!=="manyToMany")throw new u(`${s.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let d=I(l.leftForeignKey,n.caseConvention||s.databaseCaseConvention),m=I(l.rightForeignKey,n.caseConvention||s.databaseCaseConvention),p=r.map((h,g)=>({[d]:e[s.primaryKey],[m]:h[l.model.primaryKey],...o?o(h,g):{}}));class c extends at{static get table(){return l.throughModel}}c.databaseCaseConvention="preserve",c.modelCaseConvention="preserve",await c.dispatchModelManager(n).insertMany(p);}static async updateRecord(t,e,r={}){try{let o=this,n=o.dispatchModelManager(r);return e&&o.combineProps(t,e),await n.updateRecord(t)}catch(o){throw o instanceof u&&o.message==="MODEL_HAS_NO_PRIMARY_KEY"?new u(`${this.name}::updateRecord`,"MODEL_HAS_NO_PRIMARY_KEY"):o}}static async firstOrInsert(t,e,r={}){r.fullResponse||(r.fullResponse=false);let n=this.dispatchModelManager(r),s=await n.findOne({where:t});if(s)return r.fullResponse?{isNew:false,model:s}:s;let a=await n.insert(e);return r.fullResponse?{isNew:true,model:a}:a}static async upsert(t,e,r={updateOnConflict:true}){let o=this,n=o.dispatchModelManager(r),a=Object.keys(t).length>0?await n.findOne({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[],where:t}):null;return a?(e[o.primaryKey]=a[o.primaryKey],r.updateOnConflict?await n.updateRecord(e,{returning:r.returning}):a):await n.insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning??["*"]})}static async upsertMany(t,e,r={updateOnConflict:true}){if(!e.length)return [];let o=this,n=o.dispatchModelManager(r);if(!e.every(p=>{let c=new Set(Object.keys(p));return t.every(y=>c.has(y))}))throw new u("Model::upsertMany","CONFLICT_COLUMNS_NOT_PRESENT_IN_DATA");let s=Object.keys(e[0]),a=await n.upsertMany(t,s,e,{ignoreHooks:r.ignoreHooks,returning:r.returning,updateOnConflict:r.updateOnConflict??true}),l=o.sqlInstance.getDbType();if(wl.includes(l))return await le(a,o,r.returning);let d=n.query();r.returning?.length&&d.select(...r.returning);let m=new Map;return t.forEach(p=>{e.forEach(c=>{m.set(p,[...m.get(p)||[],c[p]]);});}),d.where(p=>{t.forEach(c=>{p.orWhereIn(c,m.get(c)||[]);});}),d.many({ignoreHooks:r.ignoreHooks?["afterFetch","beforeFetch"]:[]})}static async deleteRecord(t,e){return this.dispatchModelManager(e).deleteRecord(t)}static async softDelete(t,e,r){let o=this,{column:n=o.softDeleteColumn,value:s=o.softDeleteValue}=e||{};return t[n]=s,await o.dispatchModelManager({trx:r?.trx,connection:r?.connection}).updateRecord(t),typeof s=="string"?(t[n]=new Date(s),t):(t[n]=s,t)}static async truncate(t={}){return this.dispatchModelManager(t).query().truncate()}static async getTableInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getTableInfo(t.table)}static async getIndexInfo(){let t=this;return t.establishConnection(),t.sqlInstance.getIndexInfo(t.table)}static async getTableSchema(){let t=this;return t.establishConnection(),t.sqlInstance.getTableSchema(t.table)}static combineProps(t,e){for(let r in e)Object.assign(t,{[r]:e[r]});}static getColumns(){return ft(this)}static getRelations(){return Cl(this)}static getIndexes(){return _l(this)}static getUniques(){return Ol(this)}static column(t,...e){A(...e)(this.prototype,t);}static hasOne(t,...e){Nl(...e)(this.prototype,t);}static hasMany(t,...e){Ml(...e)(this.prototype,t);}static belongsTo(t,...e){Sl(...e)(this.prototype,t);}static manyToMany(t,...e){ql(...e)(this.prototype,t);}static establishConnection(){let t=ne.getInstance();if(!t)throw new u("sqlInstance not initialized, did you defined it in SqlDataSource.connect static method?","CONNECTION_NOT_ESTABLISHED");this.sqlInstance=t;}static dispatchModelManager(t){if(t?.connection)return t.connection.getModelManager(this);if(t?.trx)return t.trx.sql.getModelManager(this);let e=this;return e.establishConnection(),e.sqlInstance.getModelManager(e)}async save(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new u(r.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s={[o]:n},a=e,l=await r.upsert(s,a,{updateOnConflict:true,...t});return r.combineProps(this,l),this}async update(t,e={}){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new u(o.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new u(o.name+"::update","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.updateRecord(r,t,e);}async softDelete(t,e){let r=this,o=r.constructor,n=o.primaryKey;if(!n)throw new u(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY");if(!r[n])throw new u(o.name+"::softDelete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await o.softDelete(r,t,e);}async delete(t={}){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new u(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new u(r.name+"::delete","MODEL_HAS_NO_PRIMARY_KEY_VALUE");await r.deleteRecord(this,t);}async refresh(t){let e=this,r=e.constructor,o=r.primaryKey;if(!o)throw new u(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY");if(!e[o])throw new u(r.name+"::refresh","MODEL_HAS_NO_PRIMARY_KEY_VALUE");let s=await r.refresh(this,t);return r.combineProps(this,s),this}};at.softDeleteColumn="deletedAt",at.softDeleteValue=ae();var Z=at;var fe=class{constructor(t,e){this.model=Z;this.columnName="";this.relatedModel="";this.model=t,this.columnName=e,this.relatedModel=this.model.table;}};var ir=class extends fe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="belongsTo";}};var ar=class extends fe{constructor(e,r,o){super(e,r);this.type="hasMany";this.foreignKey=o,this.type="hasMany";}};var lr=class extends fe{constructor(t,e,r){super(t,e),this.foreignKey=r,this.type="hasOne";}};var dr=class extends fe{constructor(e,r,o){super(e,r);this.type="manyToMany";this.primaryModel=o.primaryModel,this.relatedModel=e.table,this.throughModel=o.throughModel,this.leftForeignKey=o.leftForeignKey,this.rightForeignKey=o.rightForeignKey;}};function cR(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=P.getMetadata(Pt,e.prototype)||[];o.push({columns:r,name:t??Bt(e.table,r.join("_"))}),P.defineMetadata(Pt,o,e.prototype);}}function mR(i,t){return e=>{let r=Array.isArray(i)?i:[i],o=P.getMetadata(Et,e.prototype)||[];o.push({columns:r,name:t??ee(e.table,r.join("_"))}),P.defineMetadata(Et,o,e.prototype);}}function pR(i){return t=>{let e=t,r=e.query;e.query=function(...o){let n=r.bind(this).call(this,...o);return i(n),n};}}function A(i={primaryKey:false}){let t=i?.primaryKey??false;return (e,r)=>{let o=e.constructor;if(t){if(P.getMetadata(It,e))throw new u("ModelDecorator::column","MULTIPLE_PRIMARY_KEYS_NOT_ALLOWED");P.defineMetadata(It,r,e);}let n=i.databaseName??I(r,o.databaseCaseConvention),s={columnName:r,serialize:i.serialize,prepare:i.prepare,hidden:i.hidden,isPrimary:t,primaryKeyConstraintName:i.primaryKeyConstraintName??Me(o.table,r),autoUpdate:i.autoUpdate,databaseName:n,openApi:i.openApi,type:i.type,length:i?.length,precision:i?.precision,scale:i?.scale,withTimezone:i?.withTimezone,constraints:{nullable:i.nullable,default:i.default}},a=P.getMetadata(xt,e)||[];a.push(s),P.defineMetadata(xt,a,e);}}A.primary=bd;A.date=_d;A.boolean=Rd;A.json=Od;A.uuid=Nd;A.ulid=Md;A.integer=Sd;A.float=wd;A.encryption={symmetric:qd,asymmetric:Cd};function bd(i={}){return A({...i,primaryKey:true})}function wd(i={}){return A({type:"float",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseFloat(t)}})}function Sd(i={}){return A({type:"integer",...i,serialize:t=>{if(t!==void 0)return t===null?null:typeof t=="number"?t:typeof t=="string"?+t:Number.parseInt(t)}})}function Nd(i={}){return A({type:"uuid",...i,prepare:t=>t||ge.randomUUID()})}function Md(i={}){return A({type:"ulid",...i,prepare:t=>t||qs()})}function qd(i){return A({...i,prepare:t=>t&&ws(i.key,t),serialize:t=>t&&Ss(i.key,t)})}function Cd(i){return A({...i,prepare:t=>t&&Ns(i.publicKey,t),serialize:t=>t&&Ms(i.privateKey,t)})}function Rd(i={}){return A({type:"boolean",...i,serialize:t=>!!t,prepare:t=>!!t})}function _d(i={}){let{format:t="ISO",timezone:e="UTC",autoUpdate:r=false,autoCreate:o=false,...n}=i;return A({type:"datetime",...n,autoUpdate:r,prepare:s=>s?r?mt(new Date,t,e):typeof s=="string"?s:mt(s,t,e):o?mt(new Date,t,e):null,serialize:s=>{if(s!==void 0)return s===null?null:bs(s,t,e)}})}function Od(i={}){return A({type:"jsonb",...i,serialize:t=>typeof t=="string"?JSON.parse(t):t,prepare:t=>typeof t!="string"?JSON.stringify(t):t})}function ft(i){try{return P.getMetadata(xt,i.prototype)||[]}catch{return []}}function Sl(i,t,e){return (r,o)=>{let n=()=>Ne(i().table),s=()=>{let d=r.constructor.table,m=t||n();return F(d,m,i().table)},a={type:"belongsTo",columnName:o,model:i,foreignKey:t?String(t):n,constraintName:e?.constraintName??s,onUpdate:e?.onUpdate,onDelete:e?.onDelete},l=P.getMetadata(te,r)||[];l.push(a),P.defineMetadata(te,l,r);}}function Nl(i,t){return (e,r)=>{let o=()=>Ne(e.constructor.table),n={type:"hasOne",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=P.getMetadata(te,e)||[];s.push(n),P.defineMetadata(te,s,e);}}function Ml(i,t){return (e,r)=>{let o=()=>Ne(e.constructor.table),n={type:"hasMany",columnName:r,model:i,constraintName:"None",foreignKey:t?String(t):o},s=P.getMetadata(te,e)||[];s.push(n),P.defineMetadata(te,s,e);}}function ql(i,t,e,r){return (o,n)=>{let{leftForeignKey:s,rightForeignKey:a}=e??{},l=typeof t!="string",d=typeof t=="string"?t:()=>t().table,m=o.constructor.table,p=()=>Ne(m),c=()=>Ne(i().table),y=()=>F(w(d),s?String(s):p()),h={type:"manyToMany",columnName:n,model:i,constraintName:r?.constraintName??y,foreignKey:s?String(s):p,onDelete:r?.onDelete,onUpdate:r?.onUpdate,manyToManyOptions:{primaryModel:m,throughModel:d,leftForeignKey:s?String(s):p,rightForeignKey:a?String(a):c,wasModelProvided:l}},g=P.getMetadata(te,o)||[];g.push(h),P.defineMetadata(te,g,o);}}function Cl(i){return P.getMetadata(te,i.prototype)||[]}function Wt(i){return (P.getMetadata(te,i.prototype)||[]).map(e=>{let{type:r,model:o,columnName:n,foreignKey:s}=e,a=w(s),l=o();switch(r){case "belongsTo":return new ir(l,n,a);case "hasOne":return new lr(l,n,a);case "hasMany":return new ar(l,n,a);case "manyToMany":if(!e.manyToManyOptions)throw new u("ModelDecorator::getRelations","MANY_TO_MANY_RELATION_MUST_HAVE_A_THROUGH_MODEL");let d=o();return new dr(d,n,{primaryModel:e.manyToManyOptions.primaryModel,throughModel:w(e.manyToManyOptions.throughModel),leftForeignKey:w(e.manyToManyOptions.leftForeignKey),rightForeignKey:w(e.manyToManyOptions.rightForeignKey)});default:throw new u("ModelDecorator::getRelations",`UNKNOWN_RELATION_TYPE_${r}`)}})}function Rl(i){return P.getMetadata(It,i.prototype)}function _l(i){return P.getMetadata(Pt,i.prototype)||[]}function Ol(i){return P.getMetadata(Et,i.prototype)||[]}var ds=class{constructor(t,e){this.typeofModel=t,this.modelData=e;}merge(t){this.modelData={...this.modelData,...t};}async create(t){let e=this.typeofModel;if(t===1)return e.insert(this.modelData);let r=Array.from({length:t});return e.insertMany(r.map(()=>({...this.modelData})))}},Dd=(i,t)=>new ds(i,t);var lt=class extends Z{};U([A.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"createdAt"),U([A.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"updatedAt"),U([A.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],lt.prototype,"deletedAt");var us=class extends Z{};U([A.uuid({type:"uuid",primaryKey:true,openApi:{type:"string",format:"uuid",required:true}})],us.prototype,"id");var cs=class extends Z{};U([A.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],cs.prototype,"id");var Pe=class extends Z{};U([A.integer({primaryKey:true,type:"integer",openApi:{type:"number",required:true}})],Pe.prototype,"id"),U([A({type:"varchar",length:255,openApi:{type:"string",required:true}})],Pe.prototype,"email"),U([A.date({autoCreate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Pe.prototype,"createdAt"),U([A.date({autoCreate:true,autoUpdate:true,type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Pe.prototype,"updatedAt"),U([A.date({type:"timestamp",openApi:{type:"string",format:"date-time",required:true}})],Pe.prototype,"deletedAt");var{plural:xd}=dd;function Dl(i){let t=i.name,e=I(t,"snake");return xd(e)}function Al(){return {$annotations:{}}}var Ue=class extends Se{static get collection(){return this._collection||Dl(this)}static query(t={}){return this.dispatchModelManager(t).query()}static rawCollection(){return this.mongoInstance.getCurrentConnection().db().collection(this.collection)}static async find(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).find(t)}static async findOne(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOne(t)}static async findOneOrFail(t){return await this.dispatchModelManager({session:t?.session,useConnection:t?.useConnection}).findOneOrFail(t)}static async insert(t,e={}){return await this.dispatchModelManager(e).insert(t)}static async insertMany(t,e={}){return await this.dispatchModelManager(e).insertMany(t)}static async updateRecord(t,e={}){return await this.dispatchModelManager(e).updateRecord(t)}static async deleteRecord(t,e={}){await this.dispatchModelManager(e).deleteRecord(t);}static establishConnection(){let t=dt.getInstance();if(!t)throw new u("Collection::establishConnection","CONNECTION_NOT_ESTABLISHED");this.mongoInstance=t;}static dispatchModelManager(t){if(t.useConnection)return t.useConnection.getModelManager(this,t.useConnection);if(t.session)return this.mongoInstance.getModelManager(this,this.mongoInstance,t.session);let e=this;return e.establishConnection(),e.mongoInstance.getModelManager(e,e.mongoInstance)}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static property(t){gr()(this.prototype,t);}static async afterFetch(t){return t}};U([gr()],Ue.prototype,"id");async function Re(i,t,e){if(!t)return null;let r=Al(),o=Ts(i);return (!e||!e.length)&&(e=o),e.includes("id")||e.push("id"),r.$annotations||(r.$annotations={}),await Promise.all(Object.keys(t).map(async n=>{if(n==="_id"){r.id=t._id?.toString();return}if(!o.includes(n)){let a=I(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=I(n,i.modelCaseConvention);r[s]=t[n];})),Object.keys(r.$annotations).length||delete r.$annotations,await Promise.all(e.map(async n=>{if(n!=="id"&&!t.hasOwnProperty(n)){let s=I(n,i.modelCaseConvention);r[s]=null;}})),r}async function ur(i,t,e){return (await Promise.all(t.map(async o=>await Re(i,o,e)))).filter(o=>o!==null)}var cr=class{constructor(t,e,r,o=false){this.model=t,this.idObject={},this.whereObject={},this.logs=o,this.session,this.mongoDataSource=e,this.collection=this.mongoDataSource.getCurrentConnection().db().collection(this.model.collection);}async one(t={throwErrorOnNull:false}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.findOne(e,{projection:this.selectObject,limit:1,session:this.session}),o=await Re(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await this.model.afterFetch([o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new u("MongoQueryBuilder::oneOrFail","ROW_NOT_FOUND");return e}async many(t={}){t.ignoreHooks?.includes("beforeFetch")||this.model.beforeFetch(this);let e={...this.whereObject};Object.keys(this.idObject).length&&(e._id=this.idObject);let r=await this.collection.find(e,{projection:this.selectFields,sort:this.sortObject,limit:this.limitNumber,skip:this.offsetNumber,session:this.session}).toArray(),o=await ur(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await this.model.afterFetch(o)}async insert(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertOne(t,{session:this.session});if(!e.returning)return {id:r.insertedId.toString()};let o=await this.collection.findOne({_id:r.insertedId});return await Re(this.model,o,this.selectFields)}async insertMany(t,e={}){e.ignoreHooks||this.model.beforeInsert(t);let r=await this.collection.insertMany(t,{session:this.session});if(!e.returning)return Object.values(r.insertedIds).map(n=>({id:n.toString()}));let o=await this.collection.find({_id:{$in:Object.values(r.insertedIds)}}).toArray();return await ur(this.model,o,this.selectFields)}async update(t,e={}){if(e.ignoreHooks||this.model.beforeUpdate(this),(await this.collection.updateMany({_id:this.idObject,...this.whereObject},{$set:t,session:this.session})).modifiedCount===0)return [];let o=await this.collection.find({_id:Object.keys(this.idObject).length?this.idObject:void 0,...this.whereObject},{projection:this.selectFields}).toArray();return await ur(this.model,o,this.selectFields)}async delete(t={}){t.ignoreHooks||this.model.beforeDelete(this),await this.collection.deleteMany(this.whereObject,{session:this.session});}async count(t={}){return t.ignoreHooks||this.model.beforeFetch(this),this.collection.countDocuments(this.whereObject,{session:this.session})}select(t){return this.selectFields=t,this.selectObject=t.reduce((e,r)=>(e[r]=1,e),{}),this}where(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=V("mongodb");if(t==="id")return this.idObject={$eq:new s.ObjectId(n)},this;let a={[t]:{[o]:n}};return this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this}andWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=V("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$and||(this.whereObject.$and=[]),this.whereObject.$and.push(a)):this.whereObject={$and:[a]},this)}orWhere(t,e,r){let o="$eq",n;typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="$eq");let s=V("mongodb"),a={[t]:{[o]:n}};return t==="id"?(this.idObject={$eq:new s.ObjectId(n)},this):(this.whereObject?(this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(a)):this.whereObject={$or:[a]},this)}whereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereExists(t){let e={[t]:{$exists:true}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotExists(t){let e={[t]:{$exists:false}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNot(t,e){let r={[t]:{$ne:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereLike(t,e){let r={[t]:{$regex:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}andWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(r),this):(this.whereObject.$and=[r],this):(this.whereObject={$and:[r]},this)}orWhereNotLike(t,e){let r={[t]:{$not:{$regex:e}}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(r),this):(this.whereObject.$or=[r],this):(this.whereObject={$or:[r]},this)}whereIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$in:n},this}let o={[t]:{$in:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotIn(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$nin:e}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:null};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereNotNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}andWhereNotNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(e),this):(this.whereObject.$and=[e],this):(this.whereObject={$and:[e]},this)}orWhereNotNull(t){if(t==="id")return N.warn("Id cannot be null"),this;let e={[t]:{$ne:null}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(e),this):(this.whereObject.$or=[e],this):(this.whereObject={$or:[e]},this)}whereBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$gte:e[0],$lte:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereNotBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}andWhereNotBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$and?(this.whereObject.$and.push(o),this):(this.whereObject.$and=[o],this):(this.whereObject={$and:[o]},this)}orWhereNotBetween(t,e){let r=V("mongodb");if(t==="id"){let n=e.map(s=>new r.ObjectId(s));return this.idObject={$nin:n},this}let o={[t]:{$lt:e[0],$gt:e[1]}};return this.whereObject?this.whereObject.$or?(this.whereObject.$or.push(o),this):(this.whereObject.$or=[o],this):(this.whereObject={$or:[o]},this)}whereRaw(t){return this.whereObject={...this.whereObject,...t},this}andRawWhere(t){return this.whereObject={...this.whereObject,...t},this}orRawWhere(t){return this.whereObject.$or||(this.whereObject.$or=[]),this.whereObject.$or.push(t),this}sortById(t){return this.sortObject={_id:t},this}sort(t){return typeof t=="number"?(this.sortObject={_id:t},this):typeof t=="string"?(this.sortObject={[t]:1},this):Array.isArray(t)?(this.sortObject=t.reduce((e,r)=>{if(typeof r=="string")return e[r]=1,e;let o=Object.keys(r)[0],n=Object.values(r)[0];return e[o]=+n,e},{}),this):(this.sortObject=t,this)}limit(t){return this.limitNumber=t,this}offset(t){return this.offsetNumber=t,this}};var mr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=Ue,this.mongoClient=this.mongoDataSource.getCurrentConnection(),this.collectionInstance=this.mongoClient.db().collection(this.collection.collection);}async find(t){let e=this.query();return t?(t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),t.sort&&e.sort(t.sort),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),e.many({ignoreHooks:t.ignoreHooks})):e.many()}async findOne(t){let e=this.query();return t?(t.where&&Object.entries(t.where).forEach(([r,o])=>{e.where(r,o);}),e.one({ignoreHooks:t.ignoreHooks})):e.oneOrFail()}async findOneOrFail(t){let e=this.query();if(!t)return e.oneOrFail();t.select&&e.select(t.select),t.where&&Object.entries(t.where).forEach(([o,n])=>{e.where(o,n);});let r=await e.one({ignoreHooks:t.ignoreHooks});if(r===null)throw t.customError?t.customError:new u("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new cr(this.collection,this.mongoDataSource,this.session,this.logs)}async insert(t,e={}){e.ignoreHooks||this.collection.beforeInsert(t);let o=(await this.collectionInstance.insertOne(t)).insertedId,n=await this.collectionInstance.findOne({_id:o},{session:this.session});return await Re(this.collection,n)}async insertMany(t,e={}){e.ignoreHooks||t.forEach(s=>{this.collection.beforeInsert(s);});let o=(await this.collectionInstance.insertMany(t)).insertedIds,n=await this.collectionInstance.find({_id:{$in:Object.values(o)}},{session:this.session}).toArray();return Promise.all(n.map(async s=>await Re(this.collection,s)))}async updateRecord(t){let e=t.id;if(!e)throw new u("CollectionManager::updateRecord","ROW_NOT_FOUND");let r=await import('mongodb');if((await this.collectionInstance.updateOne({_id:new r.ObjectId(e)},{$set:t})).modifiedCount===0)throw new u("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await Re(this.collection,n)}async deleteRecord(t){let e=t.id;if(!e)throw new u("CollectionManager::deleteRecord","ROW_NOT_FOUND");let r=await import('mongodb');return await this.collectionInstance.deleteOne({_id:new r.ObjectId(e)},{session:this.session}),t}};var Ee=class Ee extends ve{constructor(t,e){super({type:"mongo"}),this.url=t,this.isConnected=false,this.mongoClient=e;}getCurrentConnection(){return this.mongoClient}static async connect(t,e,r){if(!t&&(t=M.MONGO_URL,!t))throw new u("MongoDataSource::connect url is required to connect to mongo database and was not provided in the options nor the environment variables","REQUIRED_VALUE_NOT_SET");let o=(await Ie.getDriver("mongo")).client,n=new o.MongoClient(t,e);return await n.connect(),this.instance=new Ee(t,n),this.instance.isConnected=true,this.instance.logs=e?.logs||M.MONGO_LOGS||false,await r?.(this.instance),this.instance}static getInstance(){if(!Ee.instance)throw new u("MongoDataSource::getInstance mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return Ee.instance}startSession(){let t=this.mongoClient.startSession();return t.startTransaction(),t}static async disconnect(){if(!this.instance)throw new u("MongoDataSource::disconnect mongo database connection not established","CONNECTION_NOT_ESTABLISHED");await this.instance.disconnect();}async disconnect(){await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}static async closeConnection(){await this.disconnect();}static async useConnection(t,e){let r=(await Ie.getDriver("mongo")).client,o=new r.MongoClient(t.url,t.options);await o.connect();let n=new Ee(t.url,o);await e(n),await o.close();}static query(t){return this.getInstance().query(t)}query(t){if(!this.isConnected)throw new u("MongoDataSource::query","CONNECTION_NOT_ESTABLISHED");return this.getModelManager({_collection:t},this).query()}getModelManager(t,e,r){return new mr(t,e,r,this.logs)}};Ee.instance=null;var dt=Ee;var Q=class Q{constructor(t){this.OK="OK";this.isConnected=false,this.ioRedisConnection=t;}static get ioredis(){return this.redisDataSourceInstance.ioRedisConnection}get ioredis(){return this.ioRedisConnection}static async connect(t){if(this.isConnected)return;let e=t?.port||+M.REDIS_PORT||6379,r=await import('ioredis').catch(()=>{throw new L("ioredis")});this.redisDataSourceInstance=new Q(new r.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:e,password:t?.password||M.REDIS_PASSWORD,...t}));try{await this.redisDataSourceInstance.ioRedisConnection.ping(),this.redisDataSourceInstance.isConnected=!0,this.isConnected=!0;}catch{throw new u("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}static async getConnection(t){let e=await import('ioredis').catch(()=>{throw new L("ioredis")}),r=new e.default({host:t?.host||M.REDIS_HOST,username:t?.username||M.REDIS_USERNAME,port:t?.port||+M.REDIS_PORT||6379,password:t?.password||M.REDIS_PASSWORD,...t}),o=new Q(r);return await o.ioRedisConnection.ping(),o.isConnected=true,o}static async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.redisDataSourceInstance.ioRedisConnection.setex(t,r,e);return}await this.redisDataSourceInstance.ioRedisConnection.set(t,e);}catch{throw new u("RedisDataSource::set","SET_FAILED")}}static async get(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return this.getValue(e)}catch{throw new u("RedisDataSource::get","SET_FAILED")}}static async getBuffer(t){try{return await this.redisDataSourceInstance.ioRedisConnection.getBuffer(t)}catch{throw new u("RedisDataSource::getBuffer","GET_FAILED")}}static async consume(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.get(t);return await this.redisDataSourceInstance.ioRedisConnection.del(t),this.getValue(e)}catch{throw new u("RedisDataSource::consume","GET_FAILED")}}static async delete(t){try{await this.redisDataSourceInstance.ioRedisConnection.del(t);}catch{throw new u("RedisDataSource::delete","DELETE_FAILED")}}static async flushAll(){try{await this.redisDataSourceInstance.ioRedisConnection.flushall();}catch{throw new u("RedisDataSource::flushAll","FLUSH_FAILED")}}static async disconnect(){try{await this.redisDataSourceInstance.ioRedisConnection.quit(),this.redisDataSourceInstance.isConnected=!1;}catch{throw new u("RedisDataSource::disconnect","DISCONNECT_FAILED")}}async set(t,e,r){r=r?r/1e3:void 0,typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());try{if(r){await this.ioRedisConnection.setex(t,r,e);return}await this.ioRedisConnection.set(t,e);}catch{throw new u("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioRedisConnection.get(t);return Q.getValue(e)}catch{throw new u("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){try{return await this.ioRedisConnection.getBuffer(t)}catch{throw new u("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioRedisConnection.get(t);return await this.ioRedisConnection.del(t),Q.getValue(e)}catch{throw new u("RedisDataSource::consume","GET_FAILED")}}async delete(t){try{await this.ioRedisConnection.del(t);}catch{throw new u("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){try{await this.ioRedisConnection.flushall();}catch{throw new u("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){try{await this.ioRedisConnection.quit(),this.isConnected=!1;}catch{if(t)throw new u("RedisDataSource::disconnect","DISCONNECT_FAILED");N.warn("RedisDataSource::disconnect DISCONNECT_FAILED");}}static async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.lpush(t,...r)}catch{throw new u("RedisDataSource::lpush","LPUSH_FAILED")}}static async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.rpush(t,...r)}catch{throw new u("RedisDataSource::rpush","RPUSH_FAILED")}}static async lpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.lpop(t);return this.getValue(e)}catch{throw new u("RedisDataSource::lpop","LPOP_FAILED")}}static async rpop(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.rpop(t);return this.getValue(e)}catch{throw new u("RedisDataSource::rpop","RPOP_FAILED")}}static async lrange(t,e,r){try{return (await this.redisDataSourceInstance.ioRedisConnection.lrange(t,e,r)).map(n=>this.getValue(n)).filter(n=>n!==null)}catch{throw new u("RedisDataSource::lrange","LRANGE_FAILED")}}static async llen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.llen(t)}catch{throw new u("RedisDataSource::llen","LLEN_FAILED")}}async lpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.lpush(t,...r)}catch{throw new u("RedisDataSource::lpush","LPUSH_FAILED")}}async rpush(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.rpush(t,...r)}catch{throw new u("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioRedisConnection.lpop(t);return Q.getValue(e)}catch{throw new u("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioRedisConnection.rpop(t);return Q.getValue(e)}catch{throw new u("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioRedisConnection.lrange(t,e,r)).map(n=>Q.getValue(n)).filter(n=>n!==null)}catch{throw new u("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){try{return await this.ioRedisConnection.llen(t)}catch{throw new u("RedisDataSource::llen","LLEN_FAILED")}}static async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.hset(t,e,r)}catch{throw new u("RedisDataSource::hset","HSET_FAILED")}}static async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.redisDataSourceInstance.ioRedisConnection.hmset(t,r)}catch{throw new u("RedisDataSource::hmset","HMSET_FAILED")}}static async hget(t,e){try{let r=await this.redisDataSourceInstance.ioRedisConnection.hget(t,e);return this.getValue(r)}catch{throw new u("RedisDataSource::hget","HGET_FAILED")}}static async hgetall(t){try{let e=await this.redisDataSourceInstance.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=this.getValue(n);return r}catch{throw new u("RedisDataSource::hgetall","HGETALL_FAILED")}}static async hmget(t,...e){try{return (await this.redisDataSourceInstance.ioRedisConnection.hmget(t,...e)).map(o=>this.getValue(o))}catch{throw new u("RedisDataSource::hmget","HMGET_FAILED")}}static async hdel(t,...e){try{return await this.redisDataSourceInstance.ioRedisConnection.hdel(t,...e)}catch{throw new u("RedisDataSource::hdel","HDEL_FAILED")}}static async hexists(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.hexists(t,e)}catch{throw new u("RedisDataSource::hexists","HEXISTS_FAILED")}}static async hkeys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hkeys(t)}catch{throw new u("RedisDataSource::hkeys","HKEYS_FAILED")}}static async hlen(t){try{return await this.redisDataSourceInstance.ioRedisConnection.hlen(t)}catch{throw new u("RedisDataSource::hlen","HLEN_FAILED")}}async hset(t,e,r){try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.ioRedisConnection.hset(t,e,r)}catch{throw new u("RedisDataSource::hset","HSET_FAILED")}}async hmset(t,e){try{let r={};for(let[o,n]of Object.entries(e))typeof n=="object"&&!Buffer.isBuffer(n)?r[o]=JSON.stringify(n):typeof n=="boolean"?r[o]=n.toString():r[o]=String(n);return await this.ioRedisConnection.hmset(t,r)}catch{throw new u("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioRedisConnection.hget(t,e);return Q.getValue(r)}catch{throw new u("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioRedisConnection.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=Q.getValue(n);return r}catch{throw new u("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioRedisConnection.hmget(t,...e)).map(o=>Q.getValue(o))}catch{throw new u("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){try{return await this.ioRedisConnection.hdel(t,...e)}catch{throw new u("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){try{return await this.ioRedisConnection.hexists(t,e)}catch{throw new u("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){try{return await this.ioRedisConnection.hkeys(t)}catch{throw new u("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){try{return await this.ioRedisConnection.hlen(t)}catch{throw new u("RedisDataSource::hlen","HLEN_FAILED")}}static async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.sadd(t,...r)}catch{throw new u("RedisDataSource::sadd","SADD_FAILED")}}static async smembers(t){try{return (await this.redisDataSourceInstance.ioRedisConnection.smembers(t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::smembers","SMEMBERS_FAILED")}}static async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.srem(t,...r)}catch{throw new u("RedisDataSource::srem","SREM_FAILED")}}static async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.redisDataSourceInstance.ioRedisConnection.sismember(t,e)}catch{throw new u("RedisDataSource::sismember","SISMEMBER_FAILED")}}static async scard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.scard(t)}catch{throw new u("RedisDataSource::scard","SCARD_FAILED")}}static async sinter(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sinter(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sinter","SINTER_FAILED")}}static async sunion(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sunion(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sunion","SUNION_FAILED")}}static async sdiff(...t){try{return (await this.redisDataSourceInstance.ioRedisConnection.sdiff(...t)).map(r=>this.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sdiff","SDIFF_FAILED")}}async sadd(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.sadd(t,...r)}catch{throw new u("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioRedisConnection.smembers(t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::smembers","SMEMBERS_FAILED")}}async srem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.srem(t,...r)}catch{throw new u("RedisDataSource::srem","SREM_FAILED")}}async sismember(t,e){try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.ioRedisConnection.sismember(t,e)}catch{throw new u("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){try{return await this.ioRedisConnection.scard(t)}catch{throw new u("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioRedisConnection.sinter(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioRedisConnection.sunion(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioRedisConnection.sdiff(...t)).map(r=>Q.getValue(r)).filter(r=>r!==null)}catch{throw new u("RedisDataSource::sdiff","SDIFF_FAILED")}}static async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.redisDataSourceInstance.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.redisDataSourceInstance.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new u("RedisDataSource::zadd","ZADD_FAILED")}}static async zrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrange","ZRANGE_FAILED")}}static async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=this.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.redisDataSourceInstance.ioRedisConnection.zrevrange(t,e,r),n.map(s=>this.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}static async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.redisDataSourceInstance.ioRedisConnection.zrem(t,...r)}catch{throw new u("RedisDataSource::zrem","ZREM_FAILED")}}static async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.redisDataSourceInstance.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new u("RedisDataSource::zscore","ZSCORE_FAILED")}}static async zcard(t){try{return await this.redisDataSourceInstance.ioRedisConnection.zcard(t)}catch{throw new u("RedisDataSource::zcard","ZCARD_FAILED")}}async zadd(t,e,r){try{if(typeof e=="number"&&r!==void 0){let o=r;return typeof r=="object"&&!Buffer.isBuffer(r)?o=JSON.stringify(r):typeof r=="boolean"&&(o=r.toString()),await this.ioRedisConnection.zadd(t,e,o)}else if(Array.isArray(e)){let o=[];for(let[n,s]of e)o.push(n),typeof s=="object"&&!Buffer.isBuffer(s)?o.push(JSON.stringify(s)):typeof s=="boolean"?o.push(s.toString()):o.push(s);return await this.ioRedisConnection.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new u("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Q.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrange(t,e,r),n.map(s=>Q.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioRedisConnection.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=Q.getValue(n[a]),d=Number(n[a+1]);l!==null&&s.push({value:l,score:d});}return s}return n=await this.ioRedisConnection.zrevrange(t,e,r),n.map(s=>Q.getValue(s)).filter(s=>s!==null)}catch{throw new u("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}async zrem(t,...e){try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioRedisConnection.zrem(t,...r)}catch{throw new u("RedisDataSource::zrem","ZREM_FAILED")}}async zscore(t,e){try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.ioRedisConnection.zscore(t,e);return r!==null?Number(r):null}catch{throw new u("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){try{return await this.ioRedisConnection.zcard(t)}catch{throw new u("RedisDataSource::zcard","ZCARD_FAILED")}}static async subscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.subscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("message",e);}catch{throw new u("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}static async unsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.unsubscribe(...t);}catch{throw new u("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}static async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.redisDataSourceInstance.ioRedisConnection.publish(t,r)}catch{throw new u("RedisDataSource::publish","PUBLISH_FAILED")}}static async psubscribe(t,e){try{await this.redisDataSourceInstance.ioRedisConnection.psubscribe(...t),this.redisDataSourceInstance.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new u("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}static async punsubscribe(...t){try{await this.redisDataSourceInstance.ioRedisConnection.punsubscribe(...t);}catch{throw new u("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async subscribe(t,e){try{await this.ioRedisConnection.subscribe(...t),this.ioRedisConnection.on("message",e);}catch{throw new u("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){try{await this.ioRedisConnection.unsubscribe(...t);}catch{throw new u("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}async publish(t,e){try{let r;return typeof e=="object"&&!Buffer.isBuffer(e)?r=JSON.stringify(e):typeof e=="boolean"||typeof e=="number"?r=e.toString():Buffer.isBuffer(e)?r=e:r=String(e),await this.ioRedisConnection.publish(t,r)}catch{throw new u("RedisDataSource::publish","PUBLISH_FAILED")}}async psubscribe(t,e){try{await this.ioRedisConnection.psubscribe(...t),this.ioRedisConnection.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new u("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){try{await this.ioRedisConnection.punsubscribe(...t);}catch{throw new u("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}static async exists(t){try{return await this.redisDataSourceInstance.ioRedisConnection.exists(t)}catch{throw new u("RedisDataSource::exists","EXISTS_FAILED")}}static async expire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expire(t,e)}catch{throw new u("RedisDataSource::expire","EXPIRE_FAILED")}}static async expireat(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.expireat(t,e)}catch{throw new u("RedisDataSource::expireat","EXPIREAT_FAILED")}}static async pexpire(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.pexpire(t,e)}catch{throw new u("RedisDataSource::pexpire","PEXPIRE_FAILED")}}static async ttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.ttl(t)}catch{throw new u("RedisDataSource::ttl","TTL_FAILED")}}static async pttl(t){try{return await this.redisDataSourceInstance.ioRedisConnection.pttl(t)}catch{throw new u("RedisDataSource::pttl","PTTL_FAILED")}}static async persist(t){try{return await this.redisDataSourceInstance.ioRedisConnection.persist(t)}catch{throw new u("RedisDataSource::persist","PERSIST_FAILED")}}static async keys(t){try{return await this.redisDataSourceInstance.ioRedisConnection.keys(t)}catch{throw new u("RedisDataSource::keys","KEYS_FAILED")}}static async rename(t,e){try{return await this.redisDataSourceInstance.ioRedisConnection.rename(t,e)}catch{throw new u("RedisDataSource::rename","RENAME_FAILED")}}static async type(t){try{return await this.redisDataSourceInstance.ioRedisConnection.type(t)}catch{throw new u("RedisDataSource::type","TYPE_FAILED")}}async exists(t){try{return await this.ioRedisConnection.exists(t)}catch{throw new u("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){try{return await this.ioRedisConnection.expire(t,e)}catch{throw new u("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){try{return await this.ioRedisConnection.expireat(t,e)}catch{throw new u("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){try{return await this.ioRedisConnection.pexpire(t,e)}catch{throw new u("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){try{return await this.ioRedisConnection.ttl(t)}catch{throw new u("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){try{return await this.ioRedisConnection.pttl(t)}catch{throw new u("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){try{return await this.ioRedisConnection.persist(t)}catch{throw new u("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){try{return await this.ioRedisConnection.keys(t)}catch{throw new u("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){try{return await this.ioRedisConnection.rename(t,e)}catch{throw new u("RedisDataSource::rename","RENAME_FAILED")}}async type(t){try{return await this.ioRedisConnection.type(t)}catch{throw new u("RedisDataSource::type","TYPE_FAILED")}}static getValue(t){if(!t)return null;try{return JSON.parse(t)}catch{}return t==="true"||t==="false"?!!t:Number.isNaN(Number(t))?t:Number(t)}};Q.OK="OK";var ms=Q;var ps=class{constructor(t){this.dbType=t,this.migrationName=ut.basename(fileURLToPath(import.meta.url)),this.schema=new re(this.dbType);}};async function Il(i,t){let e=ut.isAbsolute(i)?i:ut.resolve(process.cwd(),i),{mod:r}=await bundleRequire({filepath:e,format:"esm",preserveTemporaryFile:false,esbuildOptions:{keepNames:true,sourcemap:true},tsconfig:"./tsconfig.json",external:["ioredis","mongodb","pg","mysql2","sqlite3","bundle-require","esbuild","sql-formatter","sql-highlight","reflect-metadata","pluralize","dayjs","async-mutex","commander"]});return r}var ys=class{parseGetAllTables(t,e,r){switch(t){case "mysql":case "mariadb":return Object.values(r).map(n=>n[`Tables_in_${e}`]);case "cockroachdb":case "postgres":return r.map(n=>n.table_name);default:throw new Error(`Unsupported database type: ${t}`)}}getAllTablesTemplate(t,e){switch(t){case "mysql":case "mariadb":return `SHOW TABLES FROM ${e};`;case "cockroachdb":case "postgres":return `SELECT table_name
|
|
84
84
|
FROM information_schema.tables
|
|
85
85
|
WHERE table_catalog = '${e}'
|
|
86
86
|
AND table_schema = 'public'
|