hysteria-orm 11.0.8 → 11.0.9

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/index.cjs CHANGED
@@ -123,7 +123,7 @@ ORDER BY cc.position`,bindings:[]}}},Kc=new hi;var gi=class{toSql(t){return {sql
123
123
  data_scale as numeric_scale
124
124
  FROM user_tab_columns
125
125
  WHERE table_name = '${t.table.toUpperCase()}'
126
- ORDER BY column_id`,bindings:[]}}},kc=new gi;var bi=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 h(this.model).formatStringColumn("oracledb",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new N(this.model,"oracledb").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new N(this.model,"oracledb").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("oracledb",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new N(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},Lc=new bi;var Ti=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("oracledb",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toOracle();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.size()')`:`JSON_QUERY(${t}, '${r}.size()')`}buildObjectKeysSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.keyNames()')`:`JSON_QUERY(${t}, '${r}.keyNames()')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Wc=new Ti;var Ni=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},jc=new Ni;var wi=class{toSql(t){let e=t,r=new N(this.model,"oracledb"),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}}},Fc=new wi;var Si=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=e.currParamIndex,s=[],a=e.columns.map((l,u)=>{let d=e.values[u];return d instanceof I?`${r.formatStringColumn("oracledb",l)} = ${d.rawValue}`:(s.push(d),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},Uc=new Si;var Ci=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`:${r} AND :${r+1}`;o=`${new h(this.model).formatStringColumn("oracledb",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("oracledb",t):t}},Vc=new Ci;var qi=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new N(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Jc=new qi;var _i=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("oracledb",e.column);switch(e.jsonOperator){case "=":r=`JSON_EQUAL(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "not contains":r=`NOT JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,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}}},Hc=new _i;var Ri=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 N(this.model,"oracledb"),{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 N(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},zc=new Ri;var Mi=class{toSql(t){let e=t,r=new N(this.model,"oracledb"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" /*+ MATERIALIZE */":"";return {sql:`${e.alias} as (${s}${n.sql})`,bindings:n.bindings}}},Yc=new Mi;var Ai=class{toSql(t){let e=t,r=new N(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Gc=new Ai;var Oi=class{toSql(t){let e=t,r=new N(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Zc=new Oi;var xi=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Xc=new xi;var $i=class{toSql(t){let e=t,r=new N(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" ");s=s.replace(/\s*check\s*\(.*\)\s*$/i,"").trim();let a=`alter column "${e.column}" type ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`alter column "${e.column}" drop not null`:`alter column "${e.column}" set not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, alter column "${e.column}" drop default`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=`, alter column "${e.column}" set default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},ep=new $i;var Di=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new N(this.model,"postgres"),s=[],a=[];for(let m of e.children){let{sql:c,bindings:p}=n.parse([m]);s.push(c.trim()),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},tp=new Di;var Ii=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},rp=new Ii;var Ei=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},op=new Ei;var Pi=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},np=new Pi;var vi=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},sp=new vi;var Bi=class{toSql(t){return {sql:"",bindings:[]}}},ip=new Bi;var Qi=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},ap=new Qi;var Ki=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},lp=new Ki;var ki=class{toSql(t){let e=t,r;return e.defaultValue instanceof I?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},up=new ki;var Li=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},dp=new Li;var Wi=class{toSql(t){return {sql:"",bindings:[]}}},mp=new Wi;var ji=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("postgres",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}else if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar(${a})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} uuid`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigserial`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} smallint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} double precision`,bindings:[]};if(n==="decimal"||n==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${a}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let a=e.withTimezone?" with time zone":" without time zone",l=typeof e.precision=="number"?`(${e.precision})`:"",u=`${o} timestamp${l}${a}`.trimEnd();return e.autoCreate&&(u+=" default current_timestamp"),{sql:u,bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} boolean`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} bytea`,bindings:[]};if(n==="json")return {sql:`${o} json`,bindings:[]};if(n==="jsonb")return {sql:`${o} jsonb`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} text check (${o} in (${a}))`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},cp=new ji;var Fi=class{toSql(t){return {sql:"",bindings:[]}}},pp=new Fi;var Ui=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("postgres",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("postgres",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof I?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(u=>r.formatStringColumn("postgres",S(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("postgres",S(u))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},fp=new Ui;var Vi=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new N(this.model,"postgres"),s=[],a=[];for(let b of e.children){let{sql:C,bindings:A}=n.parse([b]);if(b.folder==="constraint"){let q=s.pop()??"",O=C;if(/not null/i.test(O)||/null/i.test(O)||/default/i.test(O)){let D=`${q} ${O}`.trim();D=D.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(D),a.push(...A);continue}s.push(q),s.push(O),a.push(...A);continue}s.push(C),a.push(...A);}for(let b of e.namedConstraints){let{sql:C,bindings:A}=n.parse([b]);s.push(C),a.push(...A);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.temporary&&d.push("TEMPORARY"),e.unlogged&&d.push("UNLOGGED");let m=[];if(e.postgresWith){let b=Object.entries(e.postgresWith).map(([C,A])=>`${C}=${A}`).join(", ");b&&m.push(`WITH (${b})`);}let c=e.tablespace?`TABLESPACE ${e.tablespace}`:"",p=d.length>0?`${d.join(" ")} `:"",f=m.length>0?` ${m.join(" ")}`:"",y=c?` ${c}`:"";return {sql:`${u}${p}${o} (${l})${f}${y}`,bindings:a}}},yp=new Vi;var Ji=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode.table=="string")return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),n=r.getFromForWriteOperations("postgres",e.fromNode);if(e.returning&&e.returning.length){let s=e.returning.map(a=>r.formatStringColumn("postgres",a)).join(", ");n+=` returning ${s}`;}return {sql:n,bindings:[]}}},hp=new Ji;var Hi=class{toSql(t){return {sql:"",bindings:[]}}},gp=new Hi;var zi=class{toSql(t){return {sql:`(${t.columns.map(o=>new h(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},bp=new zi;var Yi=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Tp=new Yi;var Gi=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},Np=new Gi;var Zi=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("postgres",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("postgres",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new N(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},wp=new Zi;var Xi=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},Sp=new Xi;var ea=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Cp=new ea;var ta=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},qp=new ta;var ra=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},_p=new ra;var oa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(c=>r.formatStringColumn("postgres",c)).join(", "),l=[],u=[],d=e.currParamIndex;for(let c of e.records){let p=s.map(y=>c[y]),f=[];for(let y=0;y<s.length;y++){let T=p[y];T instanceof I?f.push(T.rawValue):(l.push(T),f.push(`$${d++}${this.formatTypeCast(T)}`));}u.push(`(${f.join(", ")})`);}let m=`${o} (${a}) values ${u.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(p=>r.formatStringColumn("postgres",p)).join(", ");m+=` returning ${c}`;}else m+=" returning *";return {sql:m,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Rp=new oa;var na=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("postgres",o),a=r.formatStringColumn("postgres",n),u=`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let m=new N(this.model,"postgres");for(let c of e.additionalConditions){let p=m.parse([c]);if(p.sql){let f=p.sql.replace(/^where\s+/i,"");u+=` and ${f}`,d.push(...p.bindings);}}}return {sql:u,bindings:d}}},Mp=new na;var sa=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},Ap=new sa;var Ph={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},ia=class{toSql(t){let e=t,r=Ph[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},Op=new ia;var aa=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},xp=new aa;var la=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(a=>r.formatStringColumn("postgres",a)).join(", ");if(e.mode==="ignore"){let a=`on conflict (${o}) do nothing`;if(e.returning&&e.returning.length){let l=e.returning.map(u=>r.formatStringColumn("postgres",u)).join(", ");a+=` returning ${l}`;}return {sql:a,bindings:[]}}let n=e.columnsToUpdate.map(a=>`${r.formatStringColumn("postgres",a)} = excluded.${r.formatStringColumn("postgres",a)}`).join(", "),s=`on conflict (${o}) do update set ${n}`;if(e.returning&&e.returning.length){let a=e.returning.map(l=>r.formatStringColumn("postgres",l)).join(", ");s+=` returning ${a}`;}return {sql:s,bindings:[]}}},$p=new la;var ua=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Dp=new ua;var da=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Ip=new da;var ma=class{toSql(t){return {sql:`SELECT
126
+ ORDER BY column_id`,bindings:[]}}},kc=new gi;var bi=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 h(this.model).formatStringColumn("oracledb",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new N(this.model,"oracledb").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new N(this.model,"oracledb").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("oracledb",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new N(this.model,"oracledb").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}},Lc=new bi;var Ti=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("oracledb",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toOracle();return r==="$"?t:`JSON_VALUE(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.size()')`:`JSON_QUERY(${t}, '${r}.size()')`}buildObjectKeysSql(t,e){let r=e.toOracle();return r==="$"?`JSON_QUERY(${t}, '$.keyNames()')`:`JSON_QUERY(${t}, '${r}.keyNames()')`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Wc=new Ti;var Ni=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("oracledb",e.fromNode),bindings:[]}}},jc=new Ni;var wi=class{toSql(t){let e=t,r=new N(this.model,"oracledb"),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}}},Fc=new wi;var Si=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("oracledb",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=e.currParamIndex,s=[],a=e.columns.map((l,u)=>{let d=e.values[u];return d instanceof I?`${r.formatStringColumn("oracledb",l)} = ${d.rawValue}`:(s.push(d),`${r.formatStringColumn("oracledb",l)} = :${n++}`)}).join(", ");return {sql:`${o} set ${a}`,bindings:s}}},Uc=new Si;var Ci=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`:${r} AND :${r+1}`;o=`${new h(this.model).formatStringColumn("oracledb",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`:${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("oracledb",e.column)} ${e.operator} :${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("oracledb",t):t}},Vc=new Ci;var qi=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new N(this.model,"oracledb"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Jc=new qi;var _i=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("oracledb",e.column);switch(e.jsonOperator){case "=":r=`JSON_EQUAL(${n}, ?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,o=[JSON.stringify(e.value)];break;case "not contains":r=`NOT JSON_EXISTS(${n}, '$?(@ == $val)' PASSING ? AS "val")`,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}}},Hc=new _i;var Ri=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 N(this.model,"oracledb"),{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 N(this.model,"oracledb"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},zc=new Ri;var Mi=class{toSql(t){let e=t,r=new N(this.model,"oracledb"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" /*+ MATERIALIZE */":"";return {sql:`${e.alias} as (${s}${n.sql})`,bindings:n.bindings}}},Yc=new Mi;var Ai=class{toSql(t){let e=t,r=new N(this.model,"postgres"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},Gc=new Ai;var Oi=class{toSql(t){let e=t,r=new N(this.model,"postgres"),{sql:o}=r.parse([e.constraint]);return {sql:`add ${o}`,bindings:[]}}},Zc=new Oi;var xi=class{toSql(t){return {sql:`add primary key (${t.columns.map(o=>`"${o}"`).join(", ")})`,bindings:[]}}},Xc=new xi;var $i=class{toSql(t){let e=t,r=new N(this.model,"postgres"),{sql:o}=r.parse([e.newType]),[,...n]=o.trim().split(/\s+/),s=n.join(" ");s=s.replace(/\s*check\s*\(.*\)\s*$/i,"").trim();let a=`alter column "${e.column}" type ${s}`;if(e.options.nullable!==void 0){let l=e.options.nullable?`alter column "${e.column}" drop not null`:`alter column "${e.column}" set not null`;a+=`, ${l}`;}if(e.options.dropDefault)a+=`, alter column "${e.column}" drop default`;else if(e.options.default!==void 0){let l=e.options.default;l===null?l="null":typeof l=="string"&&(l==="NULL"?l="null":l==="TRUE"||l==="FALSE"?l=l.toLowerCase():l=`'${l}'`),a+=`, alter column "${e.column}" set default ${l}`;}return e.options.unique!==void 0&&(e.options.unique?a+=`, add constraint "unique_${e.column}" unique ("${e.column}")`:a+=`, drop constraint "unique_${e.column}"`),{sql:a,bindings:[]}}},ep=new $i;var Di=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new N(this.model,"postgres"),s=[],a=[];for(let m of e.children){let{sql:c,bindings:p}=n.parse([m]);s.push(c.trim()),a.push(...p);}let l=s.join(", ");return {sql:`${e.ifExists?"if exists ":""}${o} ${l}`,bindings:a}}},tp=new Di;var Ii=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},rp=new Ii;var Ei=class{toSql(t){return {sql:`drop constraint "${t.constraintName}"`,bindings:[]}}},op=new Ei;var Pi=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},np=new Pi;var vi=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},sp=new vi;var Bi=class{toSql(t){return {sql:"",bindings:[]}}},ip=new Bi;var Qi=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},ap=new Qi;var Ki=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},lp=new Ki;var ki=class{toSql(t){let e=t,r;return e.defaultValue instanceof I?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},up=new ki;var Li=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},dp=new Li;var Wi=class{toSql(t){return {sql:"",bindings:[]}}},mp=new Wi;var ji=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("postgres",S(e.column)),n=e.dataType.toLowerCase();if(n==="char"){let a=e.length??1;return {sql:`${o} char(${a})`,bindings:[]}}else if(n==="varchar"){let a=e.length??255;return {sql:`${o} varchar(${a})`,bindings:[]}}else {if(n==="text"||n==="longtext"||n==="mediumtext"||n==="tinytext")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} uuid`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n==="bigint")return e.autoIncrement?{sql:`${o} bigserial`,bindings:[]}:{sql:`${o} bigint`,bindings:[]};if(n==="tinyint")return {sql:`${o} smallint`,bindings:[]};if(n==="smallint")return {sql:`${o} smallint`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="real")return {sql:`${o} real`,bindings:[]};if(n==="double")return {sql:`${o} double precision`,bindings:[]};if(n==="decimal"||n==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}else {if(n==="date")return {sql:`${o} date`,bindings:[]};if(n==="year")return {sql:`${o} smallint`,bindings:[]};if(n==="time"){let a=typeof e.precision=="number"?`(${e.precision})`:"";return {sql:`${o} time${a}`,bindings:[]}}else if(n==="datetime"||n==="timestamp"){let a=e.withTimezone?" with time zone":" without time zone",l=typeof e.precision=="number"?`(${e.precision})`:"",u=`${o} timestamp${l}${a}`.trimEnd();return e.autoCreate&&(u+=" default current_timestamp"),{sql:u,bindings:[]}}else {if(n==="boolean"||n==="bool")return {sql:`${o} boolean`,bindings:[]};if(n==="bytea"||n==="binary"||n==="varbinary"||n==="blob"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} bytea`,bindings:[]};if(n==="json")return {sql:`${o} json`,bindings:[]};if(n==="jsonb")return {sql:`${o} jsonb`,bindings:[]};if(n==="enum"){if(e.enumValues&&e.enumValues.length>0){let a=e.enumValues.map(l=>`'${l}'`).join(", ");return {sql:`${o} text check (${o} in (${a}))`,bindings:[]}}return {sql:`${o} text`,bindings:[]}}else {if(n==="integer"||n==="int")return e.autoIncrement?{sql:`${o} serial`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="geometry")return {sql:`${o} geometry`,bindings:[]};if(n==="point")return {sql:`${o} point`,bindings:[]};if(n==="linestring")return {sql:`${o} linestring`,bindings:[]};if(n==="polygon")return {sql:`${o} polygon`,bindings:[]};if(n==="multipoint")return {sql:`${o} multipoint`,bindings:[]}}}}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},cp=new ji;var Fi=class{toSql(t){return {sql:"",bindings:[]}}},pp=new Fi;var Ui=class{toSql(t){let e=t,r=new h(this.model);if(e.constraintType==="primary_key"){if(e.columns&&e.columns.length){let o=e.constraintName?`constraint "${e.constraintName}" `:"",n=(e.columns??[]).map(s=>r.formatStringColumn("postgres",S(s))).join(", ");return {sql:`${o}primary key (${n})`,bindings:[]}}return {sql:"primary key",bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length>0){let o=e.columns??[],n=e.constraintName?`constraint "${e.constraintName}" `:"",s=o.map(a=>r.formatStringColumn("postgres",S(a))).join(", ");return e.constraintName?{sql:`${n}unique (${s})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){if(e.defaultValue!==void 0){let o=e.defaultValue;return o instanceof I?{sql:`default ${o.rawValue}`,bindings:[]}:o==="NULL"||o===null?{sql:"default null",bindings:[]}:o==="TRUE"||o==="FALSE"?{sql:`default ${o.toLowerCase()}`,bindings:[]}:typeof o=="string"?{sql:`default '${o}'`,bindings:[]}:{sql:`default ${o}`,bindings:[]}}return {sql:"default null",bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.columns||!e.columns.length)return {sql:"",bindings:[]};let o=e.columns.map(u=>r.formatStringColumn("postgres",S(u))).join(", ");if(!e.references)return {sql:"",bindings:[]};let n=r.formatStringTable("postgres",e.references.table),s=e.references.columns.map(u=>r.formatStringColumn("postgres",S(u))).join(", "),l=`${e.constraintName?`constraint "${e.constraintName}" `:""}foreign key (${o}) references ${n}(${s})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${e.constraintName?`constraint "${e.constraintName}" `:""}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},fp=new Ui;var Vi=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new N(this.model,"postgres"),s=[],a=[];for(let b of e.children){let{sql:C,bindings:A}=n.parse([b]);if(b.folder==="constraint"){let q=s.pop()??"",O=C;if(/not null/i.test(O)||/null/i.test(O)||/default/i.test(O)){let D=`${q} ${O}`.trim();D=D.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(D),a.push(...A);continue}s.push(q),s.push(O),a.push(...A);continue}s.push(C),a.push(...A);}for(let b of e.namedConstraints){let{sql:C,bindings:A}=n.parse([b]);s.push(C),a.push(...A);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.temporary&&d.push("TEMPORARY"),e.unlogged&&d.push("UNLOGGED");let m=[];if(e.postgresWith){let b=Object.entries(e.postgresWith).map(([C,A])=>`${C}=${A}`).join(", ");b&&m.push(`WITH (${b})`);}let c=e.tablespace?`TABLESPACE ${e.tablespace}`:"",p=d.length>0?`${d.join(" ")} `:"",f=m.length>0?` ${m.join(" ")}`:"",y=c?` ${c}`:"";return {sql:`${u}${p}${o} (${l})${f}${y}`,bindings:a}}},yp=new Vi;var Ji=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode.table=="string")return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),n=r.getFromForWriteOperations("postgres",e.fromNode);if(e.returning&&e.returning.length){let s=e.returning.map(a=>r.formatStringColumn("postgres",a)).join(", ");n+=` returning ${s}`;}return {sql:n,bindings:[]}}},hp=new Ji;var Hi=class{toSql(t){return {sql:"",bindings:[]}}},gp=new Hi;var zi=class{toSql(t){return {sql:`(${t.columns.map(o=>new h(this.model).formatStringColumn("postgres",o)).join(", ")})`,bindings:[]}}},bp=new zi;var Yi=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},Tp=new Yi;var Gi=class{toSql(t){let e=t;return {sql:`${e.ifNotExists?"if not exists ":""}"${e.extensionName}"`,bindings:[]}}},Np=new Gi;var Zi=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("postgres",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("postgres",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new N(this.model,"postgres").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},wp=new Zi;var Xi=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("postgres",e.column),bindings:[]}}},Sp=new Xi;var ea=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Cp=new ea;var ta=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("postgres",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},qp=new ta;var ra=class{toSql(t){let e=t;return {sql:`"${e.indexName}" ${e.cascade?"cascade":""}`,bindings:[]}}},_p=new ra;var oa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(c=>r.formatStringColumn("postgres",c)).join(", "),l=[],u=[],d=e.currParamIndex;for(let c of e.records){let p=s.map(y=>c[y]),f=[];for(let y=0;y<s.length;y++){let T=p[y];T instanceof I?f.push(T.rawValue):(l.push(T),f.push(`$${d++}${this.formatTypeCast(T)}`));}u.push(`(${f.join(", ")})`);}let m=`${o} (${a}) values ${u.join(", ")}`;if(!e.disableReturning)if(e.returning&&e.returning.length){let c=e.returning.map(p=>r.formatStringColumn("postgres",p)).join(", ");m+=` returning ${c}`;}else m+=" returning *";return {sql:m,bindings:l}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Rp=new oa;var na=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("postgres",o),a=r.formatStringColumn("postgres",n),u=`${r.formatStringTable("postgres",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let m=new N(this.model,"postgres");for(let c of e.additionalConditions){let p=m.parse([c]);if(p.sql){let f=p.sql.replace(/^where\s+/i,"");u+=` and ${f}`,d.push(...p.bindings);}}}return {sql:u,bindings:d}}},Mp=new na;var sa=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.limit]}}},Ap=new sa;var Ph={for_update:"for update",for_share:"for share",for_no_key_update:"for no key update",for_key_share:"for key share"},ia=class{toSql(t){let e=t,r=Ph[e.lockType]||"for update";return e.skipLocked&&(r+=" skip locked"),e.noWait&&(r+=" nowait"),{sql:r,bindings:[]}}},Op=new ia;var aa=class{toSql(t){let e=t;return {sql:`$${e.currParamIndex}`,bindings:[e.offset]}}},xp=new aa;var la=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(a=>r.formatStringColumnBare("postgres",a)).join(", ");if(e.mode==="ignore"){let a=`on conflict (${o}) do nothing`;if(e.returning&&e.returning.length){let l=e.returning.map(u=>r.formatStringColumn("postgres",u)).join(", ");a+=` returning ${l}`;}return {sql:a,bindings:[]}}let n=e.columnsToUpdate.map(a=>`${r.formatStringColumnBare("postgres",a)} = excluded.${r.formatStringColumnBare("postgres",a)}`).join(", "),s=`on conflict (${o}) do update set ${n}`;if(e.returning&&e.returning.length){let a=e.returning.map(l=>r.formatStringColumn("postgres",l)).join(", ");s+=` returning ${a}`;}return {sql:s,bindings:[]}}},$p=new la;var ua=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Dp=new ua;var da=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Ip=new da;var ma=class{toSql(t){return {sql:`SELECT
127
127
  con.conname AS name,
128
128
  pg_get_constraintdef(con.oid) AS expression
129
129
  FROM pg_constraint con
@@ -182,12 +182,12 @@ ORDER BY column_id`,bindings:[]}}},kc=new gi;var bi=class{toSql(t){let e=t;if(e.
182
182
  FROM information_schema.columns
183
183
  WHERE table_schema = current_schema()
184
184
  AND table_name = '${t.table}'
185
- ORDER BY ordinal_position`,bindings:[]}}},Up=new Sa;var Ca=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new N(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new N(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new N(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},Vp=new Ca;var qa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toPostgres(false);return r?`${t}${r}`:t}buildExtractTextSql(t,e){if(e.isEmpty())return `${t}::text`;let r=e.toPostgres(true);return `${t}${r}`}buildArrayLengthSql(t,e){return `jsonb_array_length(${this.buildExtractSql(t,e)})`}buildObjectKeysSql(t,e){return `jsonb_object_keys(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Jp=new qa;var _a=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},Hp=new _a;var Ra=class{toSql(t){let e=t,r=new N(this.model,"postgres"),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}}},zp=new Ra;var Ma=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((u,d)=>{let m=e.currParamIndex+d-n,c=e.values[d];return c instanceof I?(n++,`${r.formatStringColumn("postgres",u)} = ${c.rawValue}`):(s.push(c),`${r.formatStringColumn("postgres",u)} = $${m}${this.formatTypeCast(c)}`)}).join(", "),l=`${o} set ${a}`;if(e.returning&&e.returning.length){let u=e.returning.map(d=>r.formatStringColumn("postgres",d)).join(", ");l+=` returning ${u}`;}return {sql:l,bindings:s}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Yp=new Ma;var Aa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`$${r} AND $${r+1}`;o=`${new h(this.model).formatStringColumn("postgres",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("postgres",t):t}},Gp=new Aa;var Oa=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new N(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Zp=new Oa;var xa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new h(this.model).formatStringColumn("postgres",e.column);switch(e.jsonOperator){case "=":o=`${s} = $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "not contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},Xp=new xa;var $a=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 N(this.model,"postgres"),{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 N(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},ef=new $a;var Da=class{toSql(t){let e=t,r=new N(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},tf=new Da;var Ia=class{toSql(t){let e=t,r=new N(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},rf=new Ia;var Ea=class{toSql(t){return {sql:"",bindings:[]}}},of=new Ea;var Pa=class{toSql(t){return {sql:"",bindings:[]}}},nf=new Pa;var va=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new N(this.model,"sqlite"),s=[],a=[],l=false;for(let c of e.children){let{sql:p,bindings:f}=n.parse([c]);if(!(!p||!p.trim())){if(c.file==="add_column")s.push(p),l=true;else if(c.file==="add_constraint"&&l){let y=s.pop()??"",T=p.replace(/^\s*add\s+/i,"").trimStart();s.push(`${y} ${T}`);}else {if(c.file==="set_not_null"||c.file==="drop_not_null")continue;if(c.file==="set_default"||c.file==="drop_default")continue;s.push(p),l=false;}a.push(...f);}}let u=s.join(", "),d=e.ifExists?"if exists ":"";return u.trim()?{sql:`${d}${o} ${u}`,bindings:a}:{sql:"",bindings:[]}}},sf=new va;var Ba=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},af=new Ba;var Qa=class{toSql(t){return {sql:"",bindings:[]}}},lf=new Qa;var Ka=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},uf=new Ka;var ka=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},df=new ka;var La=class{toSql(t){return {sql:"",bindings:[]}}},mf=new La;var Wa=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},cf=new Wa;var ja=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},pf=new ja;var Fa=class{toSql(t){let e=t,r;return e.defaultValue instanceof I?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},ff=new Fa;var Ua=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},yf=new Ua;var Va=class{toSql(t){return {sql:"",bindings:[]}}},hf=new Va;var Ja=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("sqlite",S(e.column)),n=e.dataType.toLowerCase();if(n==="bigincrement")return {sql:`${o} integer primary key autoincrement`,bindings:[]};if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return e.autoIncrement?{sql:`${o} integer primary key autoincrement`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}if(n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"){let a=`${o} text`;return (n==="datetime"||n==="timestamp")&&e.autoCreate&&(a+=" default current_timestamp"),{sql:a,bindings:[]}}else {if(n==="boolean")return {sql:`${o} integer`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} text`,bindings:[]};if(n==="enum")return {sql:`${o} text`,bindings:[]};if(n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} ${n}`,bindings:[]}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},gf=new Ja;var Ha=class{toSql(t){return {sql:"",bindings:[]}}},bf=new Ha;var za=class{toSql(t){let e=t,r=new h(this.model),o=e.constraintName?`constraint "${e.constraintName}" `:"";if(e.constraintType==="primary_key"){let n=!!e.autoIncrement,s=(e.columnType||"").toLowerCase();return n&&(s==="integer"||s==="bigint")?{sql:`${o}primary key autoincrement`,bindings:[]}:{sql:`${o}primary key`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length){let n=e.columns.map(s=>r.formatStringColumn("sqlite",S(s))).join(", ");return e.constraintName?{sql:`${o}unique (${n})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let n=e.defaultValue;return n instanceof I?{sql:`default ${n.rawValue}`,bindings:[]}:n==="NULL"||n===null?{sql:"default null",bindings:[]}:n==="TRUE"||n==="FALSE"?{sql:`default ${n.toLowerCase()}`,bindings:[]}:typeof n=="string"?{sql:`default '${n}'`,bindings:[]}:{sql:`default ${n}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let n=(e.columns??[]).map(u=>r.formatStringColumn("sqlite",S(u))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(u=>r.formatStringColumn("sqlite",S(u))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${o}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Tf=new za;var Ya=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new N(this.model,"sqlite"),s=[],a=[];for(let y of e.children){let{sql:T,bindings:b}=n.parse([y]);if(y.folder==="constraint"){let C=s.pop()??"",A=T;if(/not null/i.test(A)||/null/i.test(A)||/default/i.test(A)||/primary key/i.test(A)){let q=`${C} ${A}`.trim();q=q.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(q),a.push(...b);continue}s.push(C),s.push(A),a.push(...b);continue}s.push(T),a.push(...b);}for(let y of e.namedConstraints){let{sql:T,bindings:b}=n.parse([y]);s.push(T),a.push(...b);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.sqliteTemporary&&d.push("TEMPORARY");let m=d.length>0?`${d.join(" ")} `:"",c=e.withoutRowId?" WITHOUT ROWID":"",p=e.strict?" STRICT":"";return {sql:`${u}${m}${o} (${l})${c}${p}`,bindings:a}}},Nf=new Ya;var Ga=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("sqlite",e.fromNode),bindings:[]}}},wf=new Ga;var Za=class{toSql(t){return {sql:"distinct",bindings:[]}}},Sf=new Za;var Xa=class{toSql(t){return R.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Cf=new Xa;var el=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},qf=new el;var tl=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},_f=new tl;var rl=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("sqlite",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("sqlite",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new N(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Rf=new rl;var ol=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},Mf=new ol;var nl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Af=new nl;var sl=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Of=new sl;var il=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},xf=new il;var al=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(m=>r.formatStringColumn("sqlite",m)).join(", "),l=[],u=[];for(let m of e.records){let c=s.map(f=>m[f]),p=[];for(let f of c)f instanceof I?p.push(f.rawValue):(l.push(f),p.push("?"));u.push(`(${p.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${u.join(", ")}`,bindings:l}}},$f=new al;var ll=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("sqlite",o),a=r.formatStringColumn("sqlite",n),u=`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let m=new N(this.model,"sqlite");for(let c of e.additionalConditions){let p=m.parse([c]);if(p.sql){let f=p.sql.replace(/^where\s+/i,"");u+=` and ${f}`,d.push(...p.bindings);}}}return {sql:u,bindings:d}}},Df=new ll;var ul=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},If=new ul;var dl=class{toSql(t){return {sql:"",bindings:[]}}},Ef=new dl;var ml=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Pf=new ml;var cl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(s=>r.formatStringColumn("sqlite",s)).join(", ");if(e.mode==="ignore")return {sql:`ON CONFLICT (${o}) DO NOTHING`,bindings:[]};let n=e.columnsToUpdate.map(s=>`${r.formatStringColumn("sqlite",s)} = EXCLUDED.${r.formatStringColumn("sqlite",s)}`).join(", ");return {sql:`ON CONFLICT (${o}) DO UPDATE SET ${n}`,bindings:[]}}},vf=new cl;var pl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Bf=new pl;var fl=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Qf=new fl;var yl=class{toSql(t){return {sql:"SELECT 1 WHERE 0",bindings:[]}}},Kf=new yl;var hl=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},kf=new hl;var gl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Lf=new gl;var bl=class{toSql(t){return {sql:"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name",bindings:[]}}},Wf=new bl;var Tl=class{toSql(t){return {sql:`SELECT sql FROM sqlite_master WHERE type='table' AND name='${t.table}'`,bindings:[]}}},jf=new Tl;var Nl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Ff=new Nl;var wl=class{toSql(t){let e=t;return {sql:`SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='${e.table}' AND name='${e.index}'`,bindings:[]}}},Uf=new wl;var Sl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Vf=new Sl;var Cl=class{toSql(t){return {sql:`SELECT name FROM sqlite_master WHERE type='table' AND name='${t.table}'`,bindings:[]}}},Jf=new Cl;var ql=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},Hf=new ql;var _l=class{toSql(t){return {sql:`SELECT
185
+ ORDER BY ordinal_position`,bindings:[]}}},Up=new Sa;var Ca=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("postgres",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new N(this.model,"postgres").parse(t),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}if(!Array.isArray(t)){let n=new N(this.model,"postgres").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("postgres",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new N(this.model,"postgres").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},Vp=new Ca;var qa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("postgres",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toPostgres(false);return r?`${t}${r}`:t}buildExtractTextSql(t,e){if(e.isEmpty())return `${t}::text`;let r=e.toPostgres(true);return `${t}${r}`}buildArrayLengthSql(t,e){return `jsonb_array_length(${this.buildExtractSql(t,e)})`}buildObjectKeysSql(t,e){return `jsonb_object_keys(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Jp=new qa;var _a=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode=="string"?{sql:e.fromNode,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("postgres",e.fromNode),bindings:[]}}},Hp=new _a;var Ra=class{toSql(t){let e=t,r=new N(this.model,"postgres"),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}}},zp=new Ra;var Ma=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("postgres",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=0,s=[],a=e.columns.map((u,d)=>{let m=e.currParamIndex+d-n,c=e.values[d];return c instanceof I?(n++,`${r.formatStringColumn("postgres",u)} = ${c.rawValue}`):(s.push(c),`${r.formatStringColumn("postgres",u)} = $${m}${this.formatTypeCast(c)}`)}).join(", "),l=`${o} set ${a}`;if(e.returning&&e.returning.length){let u=e.returning.map(d=>r.formatStringColumn("postgres",d)).join(", ");l+=` returning ${u}`;}return {sql:l,bindings:s}}formatTypeCast(t){let e="";return Buffer.isBuffer(t)?e="::bytea":Array.isArray(t)?e="::array":typeof t=="object"&&t!==null&&!(t instanceof Date)?e="::jsonb":typeof t=="boolean"?e="::boolean":typeof t=="bigint"&&(e="::bigint"),e}},Yp=new Ma;var Aa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r=e.currParamIndex,o="",n=[];if(this.isRawNode(e.value)){let s=this.formatRawIdentifierIfPossible(e.value.rawValue);o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} ${s}`,n=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between"){let s=`$${r} AND $${r+1}`;o=`${new h(this.model).formatStringColumn("postgres",e.column)} between ${s}`,n=e.value;}else {let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} (${s})`,n=e.value;}else if(e.operator.includes("null"))o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator}`,n=[];else {if(e.value===void 0)return {sql:"",bindings:[]};o=`${new h(this.model).formatStringColumn("postgres",e.column)} ${e.operator} $${r}`,n=[e.value];}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("postgres",t):t}},Gp=new Aa;var Oa=class{toSql(t){let e=t;if(!e.nodes||!e.nodes.length)return {sql:"",bindings:[]};let r=new N(this.model,"postgres"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},Zp=new Oa;var xa=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=e.currParamIndex,o="",n=[],s=new h(this.model).formatStringColumn("postgres",e.column);switch(e.jsonOperator){case "=":o=`${s} = $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "not contains":o=`${s} @> $${r}::jsonb`,n=[JSON.stringify(e.value)];break;case "raw":o=e.column,n=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(o=`NOT (${o})`),{sql:o.trim(),bindings:n}}},Xp=new xa;var $a=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 N(this.model,"postgres"),{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 N(this.model,"postgres"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},ef=new $a;var Da=class{toSql(t){let e=t,r=new N(this.model,"postgres"),o=Array.isArray(e.body)?e.body:[e.body],n=r.parse(o.filter(Boolean),e.currParamIndex),s=e.clause==="materialized"?" materialized":"";return {sql:`${e.alias} as${s} (${n.sql})`,bindings:n.bindings}}},tf=new Da;var Ia=class{toSql(t){let e=t,r=new N(this.model,"sqlite"),{sql:o}=r.parse([e.column]),n=e.inlineConstraints;if(n&&n.length>0){let s=[];for(let a of n){let{sql:l}=r.parse([a]);s.push(l);}s.length>0&&(o+=` ${s.join(" ")}`);}return {sql:`add column ${o}`,bindings:[]}}},rf=new Ia;var Ea=class{toSql(t){return {sql:"",bindings:[]}}},of=new Ea;var Pa=class{toSql(t){return {sql:"",bindings:[]}}},nf=new Pa;var va=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:"",bindings:[]};let n=new N(this.model,"sqlite"),s=[],a=[],l=false;for(let c of e.children){let{sql:p,bindings:f}=n.parse([c]);if(!(!p||!p.trim())){if(c.file==="add_column")s.push(p),l=true;else if(c.file==="add_constraint"&&l){let y=s.pop()??"",T=p.replace(/^\s*add\s+/i,"").trimStart();s.push(`${y} ${T}`);}else {if(c.file==="set_not_null"||c.file==="drop_not_null")continue;if(c.file==="set_default"||c.file==="drop_default")continue;s.push(p),l=false;}a.push(...f);}}let u=s.join(", "),d=e.ifExists?"if exists ":"";return u.trim()?{sql:`${d}${o} ${u}`,bindings:a}:{sql:"",bindings:[]}}},sf=new va;var Ba=class{toSql(t){return {sql:`drop column "${t.column}"`,bindings:[]}}},af=new Ba;var Qa=class{toSql(t){return {sql:"",bindings:[]}}},lf=new Qa;var Ka=class{toSql(t){return {sql:`alter column "${t.column}" drop default`,bindings:[]}}},uf=new Ka;var ka=class{toSql(t){return {sql:`alter column "${t.column}" drop not null`,bindings:[]}}},df=new ka;var La=class{toSql(t){return {sql:"",bindings:[]}}},mf=new La;var Wa=class{toSql(t){let e=t;return {sql:`rename column "${e.oldName}" to "${e.newName}"`,bindings:[]}}},cf=new Wa;var ja=class{toSql(t){return {sql:`"${t.newName}"`,bindings:[]}}},pf=new ja;var Fa=class{toSql(t){let e=t,r;return e.defaultValue instanceof I?r=e.defaultValue.rawValue:e.defaultValue==="NULL"?r="null":e.defaultValue==="TRUE"||e.defaultValue==="FALSE"?r=e.defaultValue.toLowerCase():typeof e.defaultValue=="string"&&e.defaultValue!=="null"&&e.defaultValue!=="true"&&e.defaultValue!=="false"?r=`'${e.defaultValue}'`:r=String(e.defaultValue),{sql:`alter column "${e.column}" set default ${r}`,bindings:[]}}},ff=new Fa;var Ua=class{toSql(t){return {sql:`alter column "${t.column}" set not null`,bindings:[]}}},yf=new Ua;var Va=class{toSql(t){return {sql:"",bindings:[]}}},hf=new Va;var Ja=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let o=new h(this.model).formatStringColumn("sqlite",S(e.column)),n=e.dataType.toLowerCase();if(n==="bigincrement")return {sql:`${o} integer primary key autoincrement`,bindings:[]};if(n==="char"||n==="varchar")return {sql:`${o} text`,bindings:[]};if(n==="uuid")return {sql:`${o} varchar(36)`,bindings:[]};if(n==="ulid")return {sql:`${o} varchar(26)`,bindings:[]};if(n.includes("text"))return {sql:`${o} text`,bindings:[]};if(n==="integer"||n==="bigint"||n==="int")return e.autoIncrement?{sql:`${o} integer primary key autoincrement`,bindings:[]}:{sql:`${o} integer`,bindings:[]};if(n==="tinyint")return {sql:`${o} integer`,bindings:[]};if(n==="smallint")return {sql:`${o} integer`,bindings:[]};if(n==="mediumint")return {sql:`${o} integer`,bindings:[]};if(n==="float"||n==="double")return {sql:`${o} real`,bindings:[]};if(n==="decimal"||n==="numeric"){let a=e.precision??10,l=e.scale??0;return {sql:`${o} numeric(${a}, ${l})`,bindings:[]}}if(n==="date"||n==="datetime"||n==="timestamp"||n==="time"||n==="year"){let a=`${o} text`;return (n==="datetime"||n==="timestamp")&&e.autoCreate&&(a+=" default current_timestamp"),{sql:a,bindings:[]}}else {if(n==="boolean")return {sql:`${o} integer`,bindings:[]};if(n==="json"||n==="jsonb")return {sql:`${o} text`,bindings:[]};if(n==="enum")return {sql:`${o} text`,bindings:[]};if(n==="bytea"||n==="blob"||n==="binary"||n==="longblob"||n==="mediumblob"||n==="tinyblob")return {sql:`${o} blob`,bindings:[]};if(n==="geometry"||n==="point"||n==="linestring"||n==="polygon"||n==="multipoint")return {sql:`${o} ${n}`,bindings:[]}}let s=e.length?`(${e.length})`:"";return {sql:`${o} ${n}${s}`,bindings:[]}}},gf=new Ja;var Ha=class{toSql(t){return {sql:"",bindings:[]}}},bf=new Ha;var za=class{toSql(t){let e=t,r=new h(this.model),o=e.constraintName?`constraint "${e.constraintName}" `:"";if(e.constraintType==="primary_key"){let n=!!e.autoIncrement,s=(e.columnType||"").toLowerCase();return n&&(s==="integer"||s==="bigint")?{sql:`${o}primary key autoincrement`,bindings:[]}:{sql:`${o}primary key`,bindings:[]}}if(e.constraintType==="unique"){if(e.columns&&e.columns.length){let n=e.columns.map(s=>r.formatStringColumn("sqlite",S(s))).join(", ");return e.constraintName?{sql:`${o}unique (${n})`,bindings:[]}:{sql:"unique",bindings:[]}}return {sql:"unique",bindings:[]}}if(e.constraintType==="not_null")return {sql:"not null",bindings:[]};if(e.constraintType==="null")return {sql:"null",bindings:[]};if(e.constraintType==="default"){let n=e.defaultValue;return n instanceof I?{sql:`default ${n.rawValue}`,bindings:[]}:n==="NULL"||n===null?{sql:"default null",bindings:[]}:n==="TRUE"||n==="FALSE"?{sql:`default ${n.toLowerCase()}`,bindings:[]}:typeof n=="string"?{sql:`default '${n}'`,bindings:[]}:{sql:`default ${n}`,bindings:[]}}if(e.constraintType==="foreign_key"){if(!e.references)return {sql:"",bindings:[]};let n=(e.columns??[]).map(u=>r.formatStringColumn("sqlite",S(u))).join(", "),s=r.formatStringTable("sqlite",e.references.table),a=e.references.columns.map(u=>r.formatStringColumn("sqlite",S(u))).join(", "),l=`${o}foreign key (${n}) references ${s}(${a})`;return e.onDelete&&(l+=` on delete ${e.onDelete}`),e.onUpdate&&(l+=` on update ${e.onUpdate}`),{sql:l,bindings:[]}}return e.constraintType==="check"?e.checkExpression?{sql:`${o}check (${e.checkExpression})`,bindings:[]}:{sql:"",bindings:[]}:{sql:"",bindings:[]}}},Tf=new za;var Ya=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);if(!e.children||!e.children.length)return {sql:`${o} ()`,bindings:[]};let n=new N(this.model,"sqlite"),s=[],a=[];for(let y of e.children){let{sql:T,bindings:b}=n.parse([y]);if(y.folder==="constraint"){let C=s.pop()??"",A=T;if(/not null/i.test(A)||/null/i.test(A)||/default/i.test(A)||/primary key/i.test(A)){let q=`${C} ${A}`.trim();q=q.replace(/(references\s+"[^"]+"\s*\([^)]*\))\s+not null/i,"not null $1"),s.push(q),a.push(...b);continue}s.push(C),s.push(A),a.push(...b);continue}s.push(T),a.push(...b);}for(let y of e.namedConstraints){let{sql:T,bindings:b}=n.parse([y]);s.push(T),a.push(...b);}let l=s.join(", "),u=e.ifNotExists?"if not exists ":"",d=[];e.sqliteTemporary&&d.push("TEMPORARY");let m=d.length>0?`${d.join(" ")} `:"",c=e.withoutRowId?" WITHOUT ROWID":"",p=e.strict?" STRICT":"";return {sql:`${u}${m}${o} (${l})${c}${p}`,bindings:a}}},Nf=new Ya;var Ga=class{toSql(t){let e=t;return e.isRawValue&&typeof e.fromNode.table=="string"?{sql:e.fromNode.table,bindings:[]}:{sql:new h(this.model).getFromForWriteOperations("sqlite",e.fromNode),bindings:[]}}},wf=new Ga;var Za=class{toSql(t){return {sql:"distinct",bindings:[]}}},Sf=new Za;var Xa=class{toSql(t){return R.warn("SQLite does not support DISTINCT ON"),{sql:"",bindings:[]}}},Cf=new Xa;var el=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table);return {sql:`${e.ifExists?"if exists ":""}${o}`,bindings:[]}}},qf=new el;var tl=class{toSql(t){return {sql:`-- SQLite extensions are loaded dynamically, not created (extension: ${t.extensionName})`,bindings:[]}}},_f=new tl;var rl=class{toSql(t){let e=t;if(typeof e.table=="string"){let a=new h(this.model);return e.alias&&e.alias.length>0?{sql:`${a.formatStringTable("sqlite",e.table)} as "${e.alias}"`,bindings:[]}:{sql:a.formatStringTable("sqlite",e.table),bindings:[]}}let r=Array.isArray(e.table)?e.table:[e.table],n=new N(this.model,"sqlite").parse(r),s=e.alias&&e.alias.length?` as "${e.alias}"`:"";return {sql:`(${n.sql})${s}`,bindings:n.bindings}}},Rf=new rl;var ol=class{toSql(t){let e=t;return e.isRawValue?{sql:e.column,bindings:[]}:{sql:new h(this.model).formatStringColumn("sqlite",e.column),bindings:[]}}},Mf=new ol;var nl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value};let r=e.currParamIndex,o="",n=[];if(!(e.value instanceof w)&&!Array.isArray(e.value)&&(o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} $${r}`,n=[e.value]),Array.isArray(e.value)){let s=e.value.map((a,l)=>`$${r+l}`).join(", ");o=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${s})`,n=e.value;}return e.isNegated&&(o=`not (${o})`),{sql:o.trim(),bindings:n}}},Af=new nl;var sl=class{toSql(t){let e=t,o=new h(this.model).formatStringTable("sqlite",e.table),n=e.columns.map(a=>`"${a}"`).join(", ");return {sql:`${e.unique?"unique ":""}"${e.indexName}" on ${o} (${n})`,bindings:[]}}},Of=new sl;var il=class{toSql(t){return {sql:` "${t.indexName}"`,bindings:[]}}},xf=new il;var al=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.fromNode.table,bindings:[]};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.records.length)return {sql:o,bindings:[]};let n=e.records[0],s=Object.keys(n);if(!s.length)return {sql:o,bindings:[]};let a=s.map(m=>r.formatStringColumn("sqlite",m)).join(", "),l=[],u=[];for(let m of e.records){let c=s.map(f=>m[f]),p=[];for(let f of c)f instanceof I?p.push(f.rawValue):(l.push(f),p.push("?"));u.push(`(${p.join(", ")})`);}return {sql:`${o} (${a}) VALUES ${u.join(", ")}`,bindings:l}}},$f=new al;var ll=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.left;o.includes(".")||(o=`${e.table}.${o}`);let n=e.right;n.includes(".")||(n=`${this.model.table}.${n}`);let s=r.formatStringColumn("sqlite",o),a=r.formatStringColumn("sqlite",n),u=`${r.formatStringTable("sqlite",e.table)} on ${s} ${e.on?.operator} ${a}`,d=[];if(e.additionalConditions&&e.additionalConditions.length>0){let m=new N(this.model,"sqlite");for(let c of e.additionalConditions){let p=m.parse([c]);if(p.sql){let f=p.sql.replace(/^where\s+/i,"");u+=` and ${f}`,d.push(...p.bindings);}}}return {sql:u,bindings:d}}},Df=new ll;var ul=class{toSql(t){return {sql:"?",bindings:[t.limit]}}},If=new ul;var dl=class{toSql(t){return {sql:"",bindings:[]}}},Ef=new dl;var ml=class{toSql(t){return {sql:"?",bindings:[t.offset]}}},Pf=new ml;var cl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.table,bindings:[]};let r=new h(this.model),o=e.conflictColumns.map(s=>r.formatStringColumnBare("sqlite",s)).join(", ");if(e.mode==="ignore")return {sql:`ON CONFLICT (${o}) DO NOTHING`,bindings:[]};let n=e.columnsToUpdate.map(s=>`${r.formatStringColumnBare("sqlite",s)} = EXCLUDED.${r.formatStringColumnBare("sqlite",s)}`).join(", ");return {sql:`ON CONFLICT (${o}) DO UPDATE SET ${n}`,bindings:[]}}},vf=new cl;var pl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=e.direction.toLowerCase();return {sql:`${r} ${o}`,bindings:[]}}},Bf=new pl;var fl=class{toSql(t){return {sql:t.rawValue,bindings:[]}}},Qf=new fl;var yl=class{toSql(t){return {sql:"SELECT 1 WHERE 0",bindings:[]}}},Kf=new yl;var hl=class{toSql(t){return {sql:`PRAGMA foreign_key_list(${t.table})`,bindings:[]}}},kf=new hl;var gl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Lf=new gl;var bl=class{toSql(t){return {sql:"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name",bindings:[]}}},Wf=new bl;var Tl=class{toSql(t){return {sql:`SELECT sql FROM sqlite_master WHERE type='table' AND name='${t.table}'`,bindings:[]}}},jf=new Tl;var Nl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Ff=new Nl;var wl=class{toSql(t){let e=t;return {sql:`SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='${e.table}' AND name='${e.index}'`,bindings:[]}}},Uf=new wl;var Sl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Vf=new Sl;var Cl=class{toSql(t){return {sql:`SELECT name FROM sqlite_master WHERE type='table' AND name='${t.table}'`,bindings:[]}}},Jf=new Cl;var ql=class{toSql(t){return {sql:`PRAGMA index_list(${t.table})`,bindings:[]}}},Hf=new ql;var _l=class{toSql(t){return {sql:`SELECT
186
186
  'PRIMARY' as name,
187
187
  name as column_name
188
188
  FROM pragma_table_info('${t.table}')
189
189
  WHERE pk > 0
190
- ORDER BY pk`,bindings:[]}}},zf=new _l;var Rl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Yf=new Rl;var Ml=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new N(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 N(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new N(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},Gf=new Ml;var Al=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Zf=new Al;var Ol=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new h(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},Xf=new Ol;var xl=class{toSql(t){let e=t,r=new N(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}}},ey=new xl;var $l=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let u=e.values[l];return u instanceof I?`${r.formatStringColumn("sqlite",a)} = ${u.rawValue}`:(n.push(u),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},ty=new $l;var Dl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new h(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("sqlite",t):t}},ry=new Dl;var Il=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new N(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},oy=new Il;var El=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},ny=new El;var Pl=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 N(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 N(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},sy=new Pl;var vl=class{toSql(t){let e=t,r=new N(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}}},iy=new vl;var ay={mssql:{alter_table:{add_column:Iu,add_constraint:Eu,add_primary_key:Pu,alter_column_type:vu,alter_table:Bu,drop_column:Qu,drop_constraint:Ku,drop_default:ku,drop_not_null:Fu,drop_primary_key:Uu,rename_column:Vu,rename_table:Ju,set_default:Hu,set_not_null:zu,set_table_options:Yu},column:{column_type:Gu},constraint:{after:Zu,constraint:Xu},create_table:{create_table:ed},delete:{delete:td},distinct:{distinct:rd,distinct_on:od},drop_table:{drop_table:nd},extension:{create_extension:sd},from:{from:id},group_by:{group_by:ad},having:{having:ld},index_op:{create_index:ud,drop_index:dd},insert:{insert:md},join:{join:cd},limit:{limit:pd},lock:{lock:fd},offset:{offset:yd},on_duplicate:{on_duplicate:hd},order_by:{order_by:gd},raw:{raw:bd},schema:{check_constraint_info:Td,foreign_key_info:Nd,get_column_listing:wd,get_tables:Sd,has_check_constraint:Cd,has_column:qd,has_index:_d,has_primary_key:Rd,has_table:Md,index_info:Ad,primary_key_info:Od,table_info:xd},select:{select:$d,select_json:Dd},truncate:{truncate:Id},union:{union:Ed},update:{update:Pd},where:{where:vd,where_group:Bd,where_json:Qd,where_subquery:Kd},with:{with:kd}},mysql:{alter_table:{add_column:Ld,add_constraint:Wd,add_primary_key:jd,alter_column_type:Fd,alter_table:Ud,drop_column:Vd,drop_constraint:Jd,drop_default:Hd,drop_not_null:zd,drop_primary_key:Yd,rename_column:Gd,rename_table:Zd,set_default:Xd,set_not_null:em,set_table_options:tm},column:{column_type:rm},constraint:{after:om,constraint:nm},create_table:{create_table:sm},delete:{delete:im},distinct:{distinct:am,distinct_on:lm},drop_table:{drop_table:um},extension:{create_extension:dm},from:{from:mm},group_by:{group_by:cm},having:{having:pm},index_op:{create_index:fm,drop_index:ym},insert:{insert:hm},join:{join:gm},limit:{limit:bm},lock:{lock:Tm},offset:{offset:Nm},on_duplicate:{on_duplicate:wm},order_by:{order_by:Sm},raw:{raw:Cm},schema:{check_constraint_info:qm,foreign_key_info:_m,get_column_listing:Rm,get_tables:Mm,has_check_constraint:Am,has_column:Om,has_index:xm,has_primary_key:$m,has_table:Dm,index_info:Im,primary_key_info:Em,table_info:Pm},select:{select:vm,select_json:Bm},truncate:{truncate:Qm},union:{union:Km},update:{update:km},where:{where:Lm,where_group:Wm,where_json:jm,where_subquery:Fm},with:{with:Um}},oracledb:{alter_table:{add_column:Vm,add_constraint:Jm,add_primary_key:Hm,alter_column_type:zm,alter_table:Ym,drop_column:Gm,drop_constraint:Zm,drop_default:Xm,drop_not_null:ec,drop_primary_key:tc,rename_column:rc,rename_table:oc,set_default:nc,set_not_null:sc,set_table_options:ic},column:{column_type:ac},constraint:{after:lc,constraint:uc},create_table:{create_table:dc},delete:{delete:mc},distinct:{distinct:cc,distinct_on:pc},drop_table:{drop_table:fc},extension:{create_extension:yc},from:{from:hc},group_by:{group_by:gc},having:{having:bc},index_op:{create_index:Tc,drop_index:Nc},insert:{insert:wc},join:{join:Sc},limit:{limit:Cc},lock:{lock:qc},offset:{offset:_c},on_duplicate:{on_duplicate:Rc},order_by:{order_by:Mc},raw:{raw:Ac},schema:{check_constraint_info:Oc,foreign_key_info:xc,get_column_listing:$c,get_tables:Dc,has_check_constraint:Ic,has_column:Ec,has_index:Pc,has_primary_key:vc,has_table:Bc,index_info:Qc,primary_key_info:Kc,table_info:kc},select:{select:Lc,select_json:Wc},truncate:{truncate:jc},union:{union:Fc},update:{update:Uc},where:{where:Vc,where_group:Jc,where_json:Hc,where_subquery:zc},with:{with:Yc}},postgres:{alter_table:{add_column:Gc,add_constraint:Zc,add_primary_key:Xc,alter_column_type:ep,alter_table:tp,drop_column:rp,drop_constraint:op,drop_default:np,drop_not_null:sp,drop_primary_key:ip,rename_column:ap,rename_table:lp,set_default:up,set_not_null:dp,set_table_options:mp},column:{column_type:cp},constraint:{after:pp,constraint:fp},create_table:{create_table:yp},delete:{delete:hp},distinct:{distinct:gp,distinct_on:bp},drop_table:{drop_table:Tp},extension:{create_extension:Np},from:{from:wp},group_by:{group_by:Sp},having:{having:Cp},index_op:{create_index:qp,drop_index:_p},insert:{insert:Rp},join:{join:Mp},limit:{limit:Ap},lock:{lock:Op},offset:{offset:xp},on_duplicate:{on_duplicate:$p},order_by:{order_by:Dp},raw:{raw:Ip},schema:{check_constraint_info:Ep,foreign_key_info:Pp,get_column_listing:vp,get_tables:Bp,has_check_constraint:Qp,has_column:Kp,has_index:kp,has_primary_key:Lp,has_table:Wp,index_info:jp,primary_key_info:Fp,table_info:Up},select:{select:Vp,select_json:Jp},truncate:{truncate:Hp},union:{union:zp},update:{update:Yp},where:{where:Gp,where_group:Zp,where_json:Xp,where_subquery:ef},with:{with:tf}},sqlite:{alter_table:{add_column:rf,add_constraint:of,alter_column_type:nf,alter_table:sf,drop_column:af,drop_constraint:lf,drop_default:uf,drop_not_null:df,drop_primary_key:mf,rename_column:cf,rename_table:pf,set_default:ff,set_not_null:yf,set_table_options:hf},column:{column_type:gf},constraint:{after:bf,constraint:Tf},create_table:{create_table:Nf},delete:{delete:wf},distinct:{distinct:Sf,distinct_on:Cf},drop_table:{drop_table:qf},extension:{create_extension:_f},from:{from:Rf},group_by:{group_by:Mf},having:{having:Af},index_op:{create_index:Of,drop_index:xf},insert:{insert:$f},join:{join:Df},limit:{limit:If},lock:{lock:Ef},offset:{offset:Pf},on_duplicate:{on_duplicate:vf},order_by:{order_by:Bf},raw:{raw:Qf},schema:{check_constraint_info:Kf,foreign_key_info:kf,get_column_listing:Lf,get_tables:Wf,has_check_constraint:jf,has_column:Ff,has_index:Uf,has_primary_key:Vf,has_table:Jf,index_info:Hf,primary_key_info:zf,table_info:Yf},select:{select:Gf,select_json:Zf},truncate:{truncate:Xf},union:{union:ey},update:{update:ty},where:{where:ry,where_group:oy,where_json:ny,where_subquery:sy},with:{with:iy}}};var N=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(q=>!!q&&q.folder==="distinctOn"),n=!o&&t.find(q=>!!q&&q.folder==="distinct"),s=this.dbType==="mssql"?t.find(q=>!!q&&q.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(q=>q!==null&&q.folder!=="distinct"&&q.folder!=="distinctOn"),u=l.some(q=>q.folder==="offset"),d=l.some(q=>q.folder==="order_by"),m=l.find(q=>q.folder==="limit"),c=l.find(q=>q.folder==="offset"),p=this.dbType==="mssql"&&m&&!u&&!d,f=this.dbType==="mssql"&&!p&&(m||c),y=this.dbType==="oracledb"&&(m||c),T=[],b=[],C=null;p&&m&&b.push(m.limit);for(let q=0;q<l.length;q++){let O=l[q];if(p&&O.folder==="limit"||f&&(O.folder==="limit"||O.folder==="offset")||y&&(O.folder==="limit"||O.folder==="offset"))continue;O.currParamIndex=e+b.length;let D=ay[this.mapCommonDbType(this.dbType)][O.folder][O.file];if(!D)throw new Error(`Interpreter not found for ${this.dbType} ${O.keyword}`);D.model=this.model;let _=D.toSql(O);if(!_.sql||!_.sql.trim().length)continue;let v=l[q+1],$=!v||v.keyword!==O.keyword?"":v.chainsWith;if(O.folder==="lock"||O.folder==="on_duplicate"||O.folder==="schema"){T.push(`${_.sql}${$}`),b.push(..._.bindings),C=O.keyword;continue}if(C!==O.keyword||O.canKeywordBeSeenMultipleTimes){if(r)T.push(`${_.sql}${$}`);else {let V=O.keyword;if(O.folder==="with"&&this.dbType!=="mssql"){let X=q,xe=false;for(;X<l.length&&l[X].keyword===O.keyword;){let qe=l[X];if(qe.folder==="with"&&qe.clause==="recursive"){xe=true;break}X++;}xe&&(V=`${V} recursive`);}if(V==="select"){let X=p?`top (@${e}) `:"";if(o){let xe=Array.isArray(o.columns)?o.columns.join(", "):"";T.push(`select ${X}distinct on (${xe}) ${_.sql}${$}`);}else n?T.push(`select ${X}distinct ${_.sql}${$}`):T.push(`select ${X}${_.sql}${$}`);}else V==="from"&&a?T.push(`${V} ${_.sql}${a}${$}`):T.push(`${V} ${_.sql}${$}`);}C=O.keyword;}else T.push(`${_.sql}${$}`);b.push(..._.bindings);}if(f){d||T.push("order by (select null)");let q=c?.offset??0;b.push(q);let D=`offset @${e+b.length-1} rows`;if(m){b.push(m.limit);let _=e+b.length-1;D+=` fetch next @${_} rows only`;}T.push(D);}if(y){d||T.push("order by null");let q=c?.offset??0;b.push(q);let D=`offset :${e+b.length-1} rows`;if(m){b.push(m.limit);let _=e+b.length-1;D+=` fetch next :${_} rows only`;}T.push(D);}return {sql:T.join(" "),bindings:b}}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}getMssqlTableHints(t){let e=[];switch(t.lockType){case "UPDATE":e.push("UPDLOCK");break;case "SHARE":e.push("HOLDLOCK");break;case "NO_KEY_UPDATE":e.push("UPDLOCK");break;case "KEY_SHARE":e.push("HOLDLOCK");break}return t.skipLocked&&e.push("READPAST"),t.noWait&&e.push("NOWAIT"),e.length>0?` with (${e.join(", ")})`:""}};var vh=i=>{if(i==null||typeof i!="object"||i instanceof Date)return false;if(Array.isArray(i))return true;let t=Object.getPrototypeOf(i);return t===Object.prototype||t===null},h=class{constructor(t){this.model=t;this.modelColumnsMap=typeof t.getColumnsByName=="function"?t.getColumnsByName():new Map;let e=[],r=[];for(let o of this.modelColumnsMap.values())(o.prepare||o.autoUpdate)&&e.push(o),o.autoUpdate&&r.push(o);this.autoInsertColumns=e,this.autoUpdateColumns=r;}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}".*`;case "mssql":return `[${n}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??J(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}"."${a}"`;case "mssql":return `[${n}].[${a}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??J(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${e}"${r?` as "${r}"`:""}`;case "mssql":return `[${e}]${r?` as [${r}]`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let d=0;d<t.length;d++){let m=t[d],c=e[d];m!=="*"&&(o.push(m),n.push(c));}let s=new Set(o),a=null;for(let d=0;d<o.length;d++){let m=o[d],c=n[d],p=this.modelColumnsMap.get(m);if(p){if(p.prepare){let f=r==="insert"?p.prepare(c):p.prepare(c)??c;f!==null&&typeof f?.then=="function"?(a||(a=[]),a.push({index:d,promise:f})):n[d]=f;}}else vh(c)&&(n[d]=JSON.stringify(c));}if(a){let d=await Promise.all(a.map(m=>m.promise));for(let m=0;m<a.length;m++)n[a[m].index]=d[m];}let l=this.model.primaryKey,u=r==="insert"?this.autoInsertColumns:this.autoUpdateColumns;for(let d of u){let m=d.columnName;if(s.has(m)||r==="insert"&&m===l&&!d.prepare)continue;o.push(m);let c=d.prepare?await d.prepare(void 0):void 0;n.push(c??void 0);}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new N(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var rt=class extends w{constructor(e,r=false,o){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e,this.returning=o;}};var U=class extends w{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var G=class extends w{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var he=class extends w{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Me=class extends w{constructor(e,r=[],o=[],n=false,s){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o,this.returning=s;}};var ly;ly=Symbol.toStringTag;var Z=class{constructor(t,e,r,o){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=o;this[ly]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}toSql(){return this.toSqlFn()}unWrap(){return this.unWrapFn()}};var Bh=async(i,t,e,r,o,n=false)=>{let s=Object.create(t.prototype),a=null;for(let l of Object.keys(i)){let u=i[l],d=r.get(l)?.columnName??l,m=e.has(d),c=n?true:o?o.has(d):true;if(m){if(!c)continue;if(u===null){s[d]=null;continue}let p=e.get(d);if(p?.serialize){let f=p.serialize(u);f!==null&&typeof f?.then=="function"?(a||(a=[]),a.push({key:d,promise:f})):s[d]=f;continue}s[d]=u;continue}(!n||o&&o.has(d))&&(s[d]=u);}if(a){let l=await Promise.all(a.map(u=>u.promise));for(let u=0;u<a.length;u++)s[a[u].key]=l[u];}if(o)for(let l of o)l in s||(s[l]=null);return s},Ae=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),o=t.getColumnsByDatabaseName(),n=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let p=u.match(/\s+as\s+(.+)$/i);p&&s.push(p[1].trim());continue}let m=u;if(m.includes(".")&&(m=m.split(".").pop()),m==="*")continue;let c=r.get(m)?.columnName??m;s.push(c);}let a=s.length?new Set(s):null,l=await Promise.all(i.map(u=>Bh(u,t,r,o,a,n)));return l.length===1?l[0]:l};var k=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Qh=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,Kh=/^\d{4}-\d{2}-\d{2}$/,Bl=i=>typeof i!="string"?i:Qh.test(i)?new Date(i.replace(" ","T")+"Z"):Kh.test(i)?new Date(i+"T00:00:00Z"):i,kh=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),uy=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await kh(r):t[e]=r;}return t};var Ht=class extends stream.Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},dy=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((u,d)=>{n.run(i,t,function(m){m&&d(m),u(this.changes);});});if(r.mode==="fetch")return new Promise((u,d)=>{n.all(i,t,(m,c)=>{m&&d(m),(!c||!c.length)&&u([]),u(c);});});let s=r?.typeofModel;if(!s)return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);let f=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m([f]);return}let y=f?.[a]||this.lastID;if(!y)return c(new g("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[y],(b,C)=>{if(b)return c(b);m([C]);});});});if(!Array.isArray(r.models))throw new g("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let u=r.models;if(!a)return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);m(u);});});let d=[];return new Promise(async(m,c)=>{try{let p=u.map(async f=>{let y=new h(s),{columns:T,values:b}=await y.prepareColumns(Object.keys(f),Object.values(f),"insert"),C=Object.fromEntries(T.map((D,_)=>[D,b[_]])),A=new N(s,e.getDbType()),{sql:q,bindings:O}=A.parse([new G(new U(s.table),[C])]);return new Promise((D,_)=>{n.run(q,O,function(v){if(v)return _(v);let W=f[a]||this.lastID;if(!W)return _(new g("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let $=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get($,[W],(V,X)=>{if(V)return _(V);D(X);});});})});d=await Promise.all(p),m(d);}catch(p){c(p);}})}return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});})};var ot=class{constructor(t){this.observers=t??[];}add(t){this.observers.push(t);}async notifyBefore(t){for(let e of this.observers)e?.onBeforeQuery&&await e.onBeforeQuery(t);}async notifyAfter(t,e){for(let r of this.observers)r?.onAfterQuery&&(t.result??(t.result=e),await r.onAfterQuery(t));}async notifyError(t){for(let e of this.observers)e?.onQueryError&&await e.onQueryError(t);}},my=i=>{if(!i)return "OTHER";let t=i.trim().toUpperCase();return t.startsWith("SELECT")?"SELECT":t.startsWith("INSERT")?"INSERT":t.startsWith("UPDATE")?"UPDATE":t.startsWith("DELETE")?"DELETE":"OTHER"};function bt(i){let t=perf_hooks.performance.now()-i;return Math.round(t*100)/100}var z=async(i,t,e,r,o="rows",n)=>{await e.ensureConnected();let s={id:Re.randomUUID(),sql:i,params:t,model:void 0,operation:my(i),timestamp:perf_hooks.performance.now()};try{let l=e.observerChain;l&&typeof l.notifyBefore=="function"&&await l.notifyBefore(s);}catch{}n?.shouldNotLog||te(i,e.logs,t,e.inputDetails.queryFormatOptions,r);let a=perf_hooks.performance.now();switch(r){case "mysql":case "mariadb":let l=e.sqlConnection??e.getPool(),u=await Tt(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let W=bt(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:W,result:u};await $.notifyAfter(V);}}catch{}return o==="affectedRows"?u[0].affectedRows:o==="raw"?u:u[0];case "postgres":case "cockroachdb":let d=e.sqlConnection??e.getPool(),m=0,c=i.replace(/\?/g,()=>`$${++m}`),p=await Tt(()=>d.query(c,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let W=bt(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:W,result:p};await $.notifyAfter(V);}}catch{}return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let f=await Tt(()=>dy(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs),y=bt(a);try{let W=e.observerChain;if(W&&typeof W.notifyAfter=="function"){let $={...s,duration:y,result:f};await W.notifyAfter($);}}catch{}return o==="raw"?Array.isArray(f)?f:[f]:f;case "mssql":let T=e.getPool(),b=e.sqlConnection?e.sqlConnection.request():T.request();t.forEach((W,$)=>{b.input(`p${$}`,W);});let C=0,A=i.replace(/\?|@(\d+)/g,()=>`@p${C++}`),q=await Tt(()=>b.query(A),e.inputDetails.connectionPolicies?.retry,e.logs),O=bt(a);try{let W=e.observerChain;if(W&&typeof W.notifyAfter=="function"){let $={...s,duration:O,result:q};await W.notifyAfter($);}}catch{}return o==="affectedRows"?q.rowsAffected[0]:o==="raw"?q:q.recordset;case "oracledb":let D=4002,_=null,v=!!e.sqlConnection;try{_=e.sqlConnection?e.sqlConnection:await e.getConnection();let W=t.map(Bl),$=0,V=i.replace(/\?/g,()=>`:${++$}`),X=await Tt(()=>_.execute(V,W,{outFormat:D,autoCommit:!v}),e.inputDetails.connectionPolicies?.retry,e.logs),xe=bt(a);try{let yt=e.observerChain;if(yt&&typeof yt.notifyAfter=="function"){let vt={...s,duration:xe,result:X};await yt.notifyAfter(vt);}}catch{}return o==="affectedRows"?X.rowsAffected:o==="raw"?X:await Promise.all(X.rows?.map(async yt=>{let vt=await uy(yt),tu={};for(let ru in vt)tu[ru.toLowerCase()]=vt[ru];return tu})??[])}finally{_&&!v&&await _.close();}default:throw new g("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},Yt=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),m=0,c=false,p=false,f=()=>{try{a.release();}catch{}};return d.on("data",y=>{if(o.onData){m++,Promise.resolve(o.onData(l,y)).then(()=>{m--,c&&m===0&&!p&&(f(),l.end());}).catch(T=>{p=true,f(),l.destroy(T);});return}l.write(y);}),d.on("end",()=>{c=true,m===0&&!p&&(f(),l.end());}),d.on("error",y=>{p=true,f(),l.destroy(y);}),l.on("close",()=>{f();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection,l=!a,u=a??await s.connect(),d=await import('pg-query-stream').catch(()=>{throw new k("pg-query-stream")}),m=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),c=0,p=i.replace(/\?/g,()=>`$${++c}`),f=new d.default(p,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),y=u.query(f),T=0,b=false,C=false,A=q=>{if(l)try{u.release(q);}catch{}};return y.on("data",q=>{if(o.onData){T++,Promise.resolve(o.onData(m,q)).then(()=>{T--,b&&T===0&&!C&&(A(),m.end());}).catch(O=>{C=true,A(O),m.destroy(O);});return}m.write(q);}),y.on("end",()=>{b=true,T===0&&!C&&(A(),m.end());}),y.on("error",q=>{C=true,A(q),m.destroy(q);}),m}case "sqlite":{let s=e.sqlConnection??e.getPool();return new Ht(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((f,y)=>{l.input(`p${y}`,f);});let u=0,d=i.replace(/\?|@(\d+)/g,()=>`@p${u++}`),m=0,c=false,p=false;return l.on("row",f=>{if(!p){if(o.onData){m++,Promise.resolve(o.onData(a,f)).then(()=>{m--,c&&m===0&&!p&&a.end();}).catch(y=>{p=true,a.destroy(y);});return}a.write(f);}}),l.on("error",f=>{p=true,a.destroy(f);}),l.on("done",()=>{c=true,m===0&&!p&&a.end();}),l.query(d),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=4002,d=0,m=i.replace(/\?/g,()=>`:${++d}`),c=t.map(Bl),p=a.queryStream(m,c,{outFormat:u}),f=0,y=false,T=false,b=async()=>{try{await a.close();}catch{}};return p.on("data",C=>{if(T)return;let A={};for(let q in C)A[q.toLowerCase()]=C[q];if(o.onData){f++,Promise.resolve(o.onData(l,A)).then(()=>{f--,y&&f===0&&!T&&(b(),l.end());}).catch(q=>{T=true,b(),l.destroy(q);});return}l.write(A);}),p.on("end",()=>{y=true,f===0&&!T&&(b(),l.end());}),p.on("error",C=>{T=true,b(),l.destroy(C);}),l}default:throw new g("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function Tt(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++,ju(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}function cy(){return {}}var Le=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=cy(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new N(this.model,this.sqlType),this.interpreterUtils=new h(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new g(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new g(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(u=>[u,t[u]])),o=!e.returning||e.returning.length===0,n=new G(new U(this.model.table),[r],e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new Z(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(C){throw C}e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:u,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),m={};u.forEach((C,A)=>{let q=d[A];m[C]=q,t[C]??(t[C]=q);});let c=!e.returning||e.returning.length===0,{sql:p,bindings:f}=this.astParser.parse([new G(new U(this.model.table),[m],e.returning,c)]),y=await z(p,f,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let T=y[0];return T?(await this.model.afterFetch?.([T]),await Ae([T],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(u=>Object.fromEntries(Object.keys(u).map(d=>[d,u[d]]))),o=!e.returning||e.returning.length===0,n=new G(new U(this.model.table),r,e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new Z(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let T=this.model.primaryKey,b=Object.keys(t[0]||{});if(T&&!b.includes(T))return this.handleOracleIdentityInsert(t,e)}let u=new Array(t.length);await Promise.all(t.map(async(T,b)=>{let{columns:C,values:A}=await this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert"),q={};C.forEach((O,D)=>{let _=A[D];q[O]=_,T[O]??(T[O]=_);}),u[b]=q;}));let d=!e.returning||e.returning.length===0,{sql:m,bindings:c}=this.astParser.parse([new G(new U(this.model.table),u,e.returning,d)]),p=await z(m,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let f=p;return f.length?(await this.model.afterFetch?.(f),await Ae(f,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(p=>[p,c[p]]))),s=new G(new U(this.model.table),n,void 0,true),a=o.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0;new he(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",a);let u=()=>{let c=this.astParser.parse([s]);return {sql:c.sql,bindings:c.bindings}},d=()=>{let c=this.astParser.parse([s]);return {sql:Xe(this.sqlDataSource,c.sql),bindings:c.bindings}},m=()=>{let{sql:c,bindings:p}=d();return Ge(c,p)};return new Z(u,d,m,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async O=>{let{columns:D,values:_}=await this.interpreterUtils.prepareColumns(Object.keys(O),Object.values(O),"insert"),v=Object.fromEntries(D.map((W,$)=>[W,_[$]]));c.push(v);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let p=!o.returning||o.returning.length===0,f=!p&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0,{sql:y,bindings:T}=this.astParser.parse([new G(new U(this.model.table),c,void 0,true),new he(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",f)]),b=await z(y,T,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(p)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(b.length<r.length&&!(o.updateOnConflict??true)){let _=t[0],v=r.map($=>$[_]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(_,v).many()}let O=b;return await this.model.afterFetch?.(O),await Ae(O,this.model,o.returning)||[]}let C=t[0],A=r.map(O=>O[C]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(C,A).many()})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=D=>this.interpreterUtils.formatStringColumn("mssql",D),u=[],d=t.map(D=>`select ${s.map(v=>(u.push(D[v]),`@${u.length}`)).join(", ")}`),m=s.map(l).join(", "),c=d.join(" union all "),p=e.map(D=>`target.${l(D)} = source.${l(D)}`).join(" and "),f=r.filter(D=>!e.includes(D)).map(D=>`target.${l(D)} = source.${l(D)}`).join(", "),y=s.map(l).join(", "),T=s.map(D=>`source.${l(D)}`).join(", "),b=o.returning&&o.returning.length?o.returning.map(D=>`inserted.${l(D)}`).join(", "):s.map(D=>`inserted.${l(D)}`).join(", "),A=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",q=`merge into ${a} as target using (${c}) as source (${m}) on ${p} ${A} when not matched then insert (${y}) values (${T}) output ${b};`,O=await z(q,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});if(O.length===0&&!(o.updateOnConflict??true)){let D=e[0],_=n.map(W=>W[D]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(D,_).many()}return O}async updateRecord(t,e,r){let o=new Set(this.model.getColumns().map(f=>f.columnName)),n=Object.keys(e).filter(f=>o.has(f)),s=n.map(f=>e[f]),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(n,s,"update"),{primaryKey:u}=this.model;if(!u)throw new g(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let{sql:m,bindings:c}=this.astParser.parse([new Me(new U(this.model.table),a,l),new x(u,"and",false,"=",t)]);if(await z(m,c,this.sqlDataSource,this.sqlType,"affectedRows"),!r?.returning||r.returning.length===0)return;let p=await this.findOneByPrimaryKey(t,r.returning);if(!p)throw new g(this.model.name+"::updateRecord","ROW_NOT_FOUND");return p}async deleteRecord(t){if(!this.model.primaryKey)throw new g(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new x(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:o}=this.astParser.parse([new rt(new U(this.model.table)),e]);await z(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new Ie(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await Ae([a],this.model):null}return await Ae(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,f)=>{let y=a[f];l[p]=y,n[p]??(n[p]=y);});let{sql:u,bindings:d}=this.astParser.parse([new G(new U(this.model.table),[l],e.returning)]);await z(u,d,this.sqlDataSource,this.sqlType,"rows");let m=this.query().select(...e.returning||["*"]);for(let[p,f]of Object.entries(l))f!=null&&p!==o&&m.where(p,"=",f);o&&m.orderBy(o,"desc");let c=await m.one({ignoreHooks:["beforeFetch"]});if(c){let p=c;o&&p[o]&&(n[o]=p[o]),r.push(c);}else r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of n)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;o?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;o?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Nt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Su(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 g("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Gt(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 py(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var nt=i=>typeof i=="number"?i:parseFloat(i);var Zt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ge=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var st=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Xt=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var de=class extends w{constructor(e,r=[],o=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=o;}};var er=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var be=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var wt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var tr=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var it=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var rr=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var or=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var nr=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var We=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var B=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false,this.unsigned=o.unsigned,this.zerofill=o.zerofill;}};var H=class extends w{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var sr=class extends w{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var ir=class extends w{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var ar=class extends w{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var lr=class extends w{constructor(e,r,o,n=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=o,this.unique=n;}};var ur=class extends w{constructor(e,r,o){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=o??false;}};var St=class extends w{constructor(e,r=false,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 je=class extends w{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var at=class extends w{constructor(e,r,o){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=o,this.clause=e;}};var me=class extends w{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var lt=class extends w{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var Fe=class extends w{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var dr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var mr=class extends w{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Ee=class extends w{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var ie=class extends w{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var Ct=class extends w{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var cr=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var pr=class extends w{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var qt=class extends w{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var yr=class yr{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs,typeof t.getColumns=="function"?(this.modelColumns=t.getColumns(),this.modelColumnsMap=t.getColumnsByName?.()??new Map(this.modelColumns.map(r=>[r.columnName,r]))):(this.modelColumns=[],this.modelColumnsMap=yr.EMPTY_MAP);}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new Ct(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Ct(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new qt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new qt(t,"asc",true)),this}limit(t){return typeof t!="number"&&R.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new cr(t),this}offset(t){return typeof t!="number"&&R.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new pr(t),this}};yr.EMPTY_MAP=new Map;var fr=yr;var Ue=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",false,"in",e)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",false,"in",e)),this):(this.whereNodes.push(new x("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",true,"in",e)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",true,"in",e)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new x(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new x(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new x(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new x(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new x(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new x(t,"or",true,"=",e??[],true)),this}};var hr=class extends fr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ie(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ie(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ie(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ie(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ie(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ie(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var gr=class extends hr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=J(s,this.model.databaseCaseConvention);this.selectNodes.push(new me(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=J(o,this.model.databaseCaseConvention);this.selectNodes.push(new me(n));}),this}selectRaw(e){return this.selectNodes.push(new me(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":J(r,this.model.databaseCaseConvention);return this.selectNodes.push(new me(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new U(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}table(e){return this.fromNode=new U(e),this}distinct(){return this.distinctNode=new dr,this}distinctOn(...e){return this.distinctOnNode=new mr(e),this}selectJson(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Ee(e,"",r,"raw",true)),this}};var br=class extends gr{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 Q&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||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 Q&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"and",false,n,new I(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"or",false,n,new I(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof Q&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 x(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",false,"in",r)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",false,"in",r)),this):(this.whereNodes.push(new x("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 x(e,"and",true,"in",r)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",true,"in",r)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new x(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new x(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new x(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new x(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 x(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 x(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new x(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new x(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Fe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Fe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof Q)return e;let r=new Q(this.model,this.sqlDataSource),o=e(r);return o!=null&&"extractQueryNodes"in o?o:r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new ye(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new ye(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new Q(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new Q(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Tr=class extends br{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"or",false,"raw",e)),this}};var Q=class i extends Tr{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new N(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new h(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource),s=r(n),a=s!=null&&"extractQueryNodes"in s?s:n;return this.selectNodes.push(new me(a.extractQueryNodes(),o)),this}return this.selectNodes.push(new me(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>z(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new g("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await Yt(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let[s,a]=await this.executePaginateQueries(()=>this.many(),()=>n.getCount()),l=s[s.length-1],u=l?l[r.discriminator]:null;return [{paginationMetadata:py(e,a),data:s},{key:r.discriminator,value:u}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new St("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new St("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new je(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new je(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&R.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:Gt(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new g("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource),n=e(o),a=(n!=null&&"extractQueryNodes"in n?n:o).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new at("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new at("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new g("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new at("materialized",e,s.extractQueryNodes())),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new G(this.fromNode,[o],r,n),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((p,f)=>[p,a[f]]));this.insertNode=new G(this.fromNode,[l],r,n);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),m=await this.getSqlDataSource("write"),c=await z(u,d,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new G(this.fromNode,o,r,n),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async m=>{let{columns:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert");return Object.fromEntries(c.map((f,y)=>[f,p[y]]))}));this.insertNode=new G(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await z(a,l,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return d})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new G(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new he(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(l.map((y,T)=>[y,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:m,bindings:c}=this.astParser.parse([new G(new U(this.model.table),[d],void 0,true),new he(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),f=await z(m,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(f)?f:[f]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new G(new U(this.model.table),s,void 0,true),this.onDuplicateNode=new he(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async c=>{let{columns:p,values:f}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),y=Object.fromEntries(p.map((T,b)=>[T,f[b]]));a.push(y);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:u}=this.astParser.parse([new G(new U(this.model.table),a,void 0,true),new he(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),m=await z(l,u,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=v=>this.interpreterUtils.formatStringColumn("mssql",v),d=[],m=e.map(v=>`select ${a.map($=>(d.push(v[$]),`@${d.length}`)).join(", ")}`),c=a.map(u).join(", "),p=m.join(" union all "),f=r.map(v=>`target.${u(v)} = source.${u(v)}`).join(" and "),y=o.filter(v=>!r.includes(v)).map(v=>`target.${u(v)} = source.${u(v)}`).join(", "),T=a.map(u).join(", "),b=a.map(v=>`source.${u(v)}`).join(", "),C=n.returning&&n.returning.length?n.returning.map(v=>`inserted.${u(v)}`).join(", "):a.map(v=>`inserted.${u(v)}`).join(", "),q=(n.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",O=`merge into ${l} as target using (${p}) as source (${c}) on ${f} ${q} when not matched then insert (${T}) values (${b}) output ${C};`,D=await this.getSqlDataSource("write"),_=await z(O,d,D,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(_)?_:[_]}update(e,r){let o=Object.keys(e),n=Object.values(e);this.updateNode=new Me(this.fromNode,o,n,false,r);let s=r&&r.length>0;return new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:a,values:l}=await this.interpreterUtils.prepareColumns(o,n,"update");this.updateNode=new Me(this.fromNode,a,l,false,r);let{sql:u,bindings:d}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),m=await this.getSqlDataSource("write");return z(u,d,m,this.dbType,s?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:s?"fetch":"affectedRows"}})})}truncate(){return this.truncateNode=new lt(this.fromNode),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await z(e,r,o,this.dbType,"rows");})}delete(e){this.deleteNode=new rt(this.fromNode,false,e);let r=e&&e.length>0;return new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:o,bindings:n}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),s=await this.getSqlDataSource("write");return z(o,n,s,this.dbType,r?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=He()}=e||{};return this.updateNode=new Me(this.fromNode,[r],[o]),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Me(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return z(a,l,u,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return Ge(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),o=Xe(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new me("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes());return {sql:this.withQuery?`${this.withQuery} ${e}`:e,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=j(this.modelSelectedColumns),e.distinctNode=j(this.distinctNode),e.distinctOnNode=j(this.distinctOnNode),e.selectNodes=j(this.selectNodes),e.withQuery=j(this.withQuery),e.joinNodes=j(this.joinNodes),e.whereNodes=j(this.whereNodes),e.groupByNodes=j(this.groupByNodes),e.havingNodes=j(this.havingNodes),e.orderByNodes=j(this.orderByNodes),e.lockQueryNodes=j(this.lockQueryNodes),e.unionNodes=j(this.unionNodes),e.withNodes=j(this.withNodes),e.fromNode=j(this.fromNode),e.limitNode=j(this.limitNode),e.offsetNode=j(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new me("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};function fy(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:jh(i)}function jh(i){let{parentCount:t,relationType:e,hasLimitOffset:r}=i;return r&&(e==="hasMany"||e==="manyToMany")?"batched":t===1?"join":e==="manyToMany"?typeof t=="number"&&t<=10?"join":"batched":typeof t=="number"&&t<10?"join":"batched"}var Ie=class i extends Q{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Nt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[o,n]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(o,n.columnName);}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new g(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a));if(!o.length)return [];let n=await Ae(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await Yt(r,o,n,e,{onData:async(a,l)=>{let u=this.addAdditionalColumnsToModel(l),d=await Ae([u],this.model,this.modelSelectedColumns);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),a.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new g(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}upsert(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return n.upsertMany(s,a,[l],{updateOnConflict:o.updateOnConflict??true,returning:o.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=r.length>0?Object.keys(r[0]):[];return n.upsertMany(e,s,r,{updateOnConflict:o.updateOnConflict??true,returning:o.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource.getTransactionBoundSqlDataSource()??this.sqlDataSource;return new Le(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,o){return this.getModelManager(o?.trx).updateRecord(e,r,o)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let o=this.model.primaryKey;if(!o)throw new g(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,o){let{column:n=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[n]:s};return this.getModelManager(o?.trx).updateRecord(e,a,{returning:o?.returning})}async firstOrInsert(e,r,o){let n=this.getModelManager(o?.trx),s=await n.findOne({where:e,ignoreHooks:["afterFetch","beforeFetch"]});if(s)return s;let a={...e,...r};return n.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,o,n,s={}){if(Array.isArray(o)||(o=[o]),!o.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new g(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=J(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=J(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=o.map((p,f)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...n?n(p,f):{}}));class m extends ne{static get table(){return a.throughModel}}m.databaseCaseConvention="preserve",m.modelCaseConvention="preserve",await new Le(m,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let o=r.returning,n=super.update(e,o);return new Z(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),n))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new Z(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=e.returning,o=super.delete(r);return new Z(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),o))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,u]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:Gt(e,r,u),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof Q)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,o){let n,s={strategy:"auto"};typeof r=="function"?(n=r,o&&(s=o)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,n?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereExists(d),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereExists(d),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereNotExists(d),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=j(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}async processRelationsWithStrategy(e){let r=e.length,o=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),n=async s=>{let a=fy({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of o)await n(s);return}await Promise.all(o.map(n));}async loadRelationViaJoin(e,r){let o=e.relation,n=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,o,n).many({ignoreHooks:["beforeFetch","afterFetch"]});this.mapJoinedResultsToModels(a,r,o,n);}buildJoinQuery(e,r,o){let n=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)n.selectNodes.push(j(s));else for(let[s]of this.model.getColumnsByDatabaseName())n.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=j(s);this.qualifyWhereNodeColumns(a,this.model.table),n.whereNodes.push(a);}for(let s of this.groupByNodes)n.groupByNodes.push(j(s));for(let s of this.orderByNodes)n.orderByNodes.push(j(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(n.limitNode=j(this.limitNode)),this.offsetNode&&(n.offsetNode=j(this.offsetNode))),r.type){case "hasOne":case "hasMany":n.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":n.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;n.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),n.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(n,r,e,o);for(let s of e.whereNodes)n.whereNodes.push(j(s));for(let s of e.orderByNodes)n.orderByNodes.push(j(s));return n}selectRelationColumnsWithAlias(e,r,o,n){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=o.selectNodes.filter(c=>typeof c.column=="string"),m=d.some(c=>c.column==="*"||c.column.endsWith(".*"));if(d.length===0||m)for(let[c,p]of u)e.selectRaw(`${a.table}.${c} as ${s}${n}${p.columnName}`);else for(let c of d){let p=c.column,f=p.includes(".")?p.split(".").pop():p,y=u.get(f)||l.get(f),T=y?.databaseName??f,b=c.alias??y?.columnName??f;e.selectRaw(`${a.table}.${T} as ${s}${n}${b}`);}}mapJoinedResultsToModels(e,r,o,n){let{columnName:s,type:a}=o,l=o.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];u.has(m)||u.set(m,[]);let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.get(m).push(c));}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||[];});}else {let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];if(!u.has(m)){let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.set(m,c));}}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||null;});}}extractRelationDataFromRow(e,r,o){let n=`${r}${o}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(n)){let d=u.substring(n.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof x)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof ye)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Se)for(let o of e.nodes)this.qualifyWhereNodeColumns(o,r);}serializeRelationData(e,r){for(let o of Object.keys(e)){let n=r.get(o);n?.serialize&&e[o]!==null&&e[o]!==void 0&&(e[o]=n.serialize(e[o]));}}async loadRelationViaBatch(e,r){let o=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,o);}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let f=n.get(String(p));c[e.columnName]=f||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let f=s.get(String(p));c[e.columnName]=f||null;});break;case "hasMany":if(!this.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let p=c[e.foreignKey];if(!p)return;let f=String(p);a.has(f)||a.set(f,[]),a.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=a.get(String(p))||[];c[e.columnName]=f;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,m=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||J(d,this.model.modelCaseConvention);o.forEach(c=>{let p=c[m];if(p==null)return;let f=String(p);u.has(f)||u.set(f,[]),delete c[m],u.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=u.get(String(p))||[];c[e.columnName]=f;});break;default:throw new g(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=Re__default.default.randomBytes(6).toString("hex"),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(_=>_.isRawValue?_.column:`${this.interpreterUtils.formatStringColumn(this.dbType,_.column)} ${_.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(u,_=>_.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,n));s&&m.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&m.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(_=>io(_,u,e.model.table));return m.select(...c).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new g(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let f=e.limitNode?.limit,y=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(_=>_.includes(".")?_:`${r.model.table}.${_}`):[`${r.model.table}.*`];if(!f&&!y)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let b=Re__default.default.randomBytes(6).toString("hex"),C=`${r.model.table}_cte_${b}`,A=e.orderByNodes.map(_=>{if(_.isRawValue)return _.column;let v=_.column.includes(".")?_.column:`${r.model.table}.${_.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,v)} ${_.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let q=`${Re__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,O=e.with(C,_=>_.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,q]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${A}) as rn_${b}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));f&&O.whereRaw(`rn_${b} <= ${f+(y||0)}`),y&&O.whereRaw(`rn_${b} > ${y}`);let D=T.map(_=>io(_,C,e.model.table));return O.select(...D).select([`${C}.${q}`,p.leftForeignKey]).table(C);default:throw new g(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new g(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 g(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new g(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new h(r.model),a=new h(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new g(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new g(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new g(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===u.throughModel&&p.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let m=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(m).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new g(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e){let r={};return Object.entries(e).forEach(([o,n])=>{if(this.modelColumnsDatabaseNames.get(o)){r[o]=n;return}r[o]=n;}),r}};var kl=class{constructor(t,e,r){this.sqlDataSource=t,this.typeofModel=e,this.modelData=r;}merge(t){this.modelData={...this.modelData,...t};}getQueryBuilder(){return new Ie(this.typeofModel,this.sqlDataSource)}async create(t){if(t<=0)return [];let e=this.getQueryBuilder();if(t===1)return await e.insert(this.modelData,{returning:["*"]});let r=Array.from({length:t});return await e.insertMany(r.map(()=>({...this.modelData})),{returning:["*"]})}},Fh=(i,t,e)=>new kl(i,t,e);var ut=new Map,Pe=new Map,Nr=class{async get(t){return ut.get(t)}async set(t,e,r){let o=Pe.get(t);if(o&&(clearTimeout(o),Pe.delete(t)),ut.set(t,e),r){let n=setTimeout(()=>{ut.delete(t),Pe.delete(t);},r);Pe.set(t,n);}}async invalidate(t){let e=Pe.get(t);e&&(clearTimeout(e),Pe.delete(t)),ut.delete(t);}async invalidateAll(t){let e=ut.keys();for(let r of e)if(r.startsWith(t)){let o=Pe.get(r);o&&(clearTimeout(o),Pe.delete(r)),ut.delete(r);}}};var yy=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw R.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new k("ioredis")});return this.redisInstance=new t(this.ioRedisOptions),this.redisInstance}async get(t){let r=await(await this.getClient()).get(t);if(r!=null)return this.deserializeData(r)}async set(t,e,r){let o=await this.getClient(),n=this.serializeData(e);if(n){if(r){await o.set(t,n,"PX",r);return}await o.set(t,n);}}async invalidate(t){await(await this.getClient()).del(t);}async invalidateAll(t){let e=await this.getClient(),r=await e.keys(`${t}:*`);for(let o of r)await e.del(o);}serializeData(t){if(t!=null){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("base64");if(typeof t=="object"||Array.isArray(t))try{return JSON.stringify(t)}catch(e){throw R.error("RedisCacheAdapter::set failed to serialize data"),e}return String(t)}}deserializeData(t){try{return JSON.parse(t)}catch{return t}}async disconnect(){this.redisInstance&&await this.redisInstance.quit();}};var P={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},Uh=()=>{if(!eo__default.default.existsSync(".env"))return P;try{eo__default.default.readFileSync(".env","utf8").split(`
190
+ ORDER BY pk`,bindings:[]}}},zf=new _l;var Rl=class{toSql(t){return {sql:`PRAGMA table_info(${t.table})`,bindings:[]}}},Yf=new Rl;var Ml=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.quoteAliasesInRawSql(e.column),bindings:[]};let r=this.formatColumn(e.column,e.sqlFunction),o=this.formatAlias(e.alias);return {sql:`${r.sql}${o}`,bindings:r.bindings}}formatColumn(t,e){if(typeof t=="string"){let o=new h(this.model).formatStringColumn("sqlite",t),n=o;return e&&(n=`${e.toLowerCase()}(${o})`),{sql:n,bindings:[]}}if(Array.isArray(t)&&t.length>0){let n=new N(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 N(this.model,"sqlite").parse([t]),s=`(${n.sql})`;return e&&(s=`${e.toLowerCase()}${s}`),{sql:s,bindings:n.bindings}}return {sql:t.map(o=>{if(typeof o=="string"){let l=new h(this.model).formatStringColumn("sqlite",o);return e?`${e.toLowerCase()}(${l})`:l}let a=`(${new N(this.model,"sqlite").parse([o]).sql})`;return e&&(a=`${e.toLowerCase()}${a}`),a}).join(", "),bindings:[]}}formatAlias(t){return t&&t.length>0?` as "${t}"`:""}quoteAliasesInRawSql(t){return t.replace(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi,(e,r,o)=>{let n=t.slice(0,o),s=n.toLowerCase(),a=s.lastIndexOf("cast");for(;a>=0;){let l=a>0?s[a-1]:" ",u=s[a+4]||" ";if(!/[a-z0-9_]/i.test(l)&&!/[a-z0-9_]/i.test(u))break;a=s.lastIndexOf("cast",a-1);}if(a>=0){let l=n.slice(a),u=0;for(let d of l)d==="("&&u++,d===")"&&u--;if(u>0)return e}return `as "${r}"`})}},Gf=new Ml;var Al=class{toSql(t){let e=t;if(e.isRawValue)return {sql:this.formatWithAlias(e.column,e.alias),bindings:[]};let r=new h(this.model).formatStringColumn("sqlite",e.column),o=ue.from(e.jsonPath),n="";switch(e.jsonOperator){case "extract":n=this.buildExtractSql(r,o);break;case "extract_text":n=this.buildExtractTextSql(r,o);break;case "array_length":n=this.buildArrayLengthSql(r,o);break;case "object_keys":n=this.buildObjectKeysSql(r,o);break;case "raw":n=e.column;break}return {sql:this.formatWithAlias(n,e.alias),bindings:[]}}buildExtractSql(t,e){let r=e.toSqlite();return r==="$"?t:`json_extract(${t}, '${r}')`}buildExtractTextSql(t,e){return this.buildExtractSql(t,e)}buildArrayLengthSql(t,e){let r=e.toSqlite();return r==="$"?`json_array_length(${t})`:`json_array_length(${t}, '${r}')`}buildObjectKeysSql(t,e){return `json_each.key FROM json_each(${this.buildExtractSql(t,e)})`}formatWithAlias(t,e){return e&&e.length>0?`${t} as "${e}"`:t}},Zf=new Al;var Ol=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return e.keyword="",{sql:e.fromNode,bindings:[]};let r=new h(this.model).getFromForWriteOperations("sqlite",e.fromNode);return e.keyword="DELETE FROM",{sql:r,bindings:[]}}},Xf=new Ol;var xl=class{toSql(t){let e=t,r=new N(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}}},ey=new xl;var $l=class{toSql(t){let e=t;if(e.isRawValue&&typeof e.fromNode=="string")return {sql:e.fromNode,bindings:e.values};let r=new h(this.model),o=r.getFromForWriteOperations("sqlite",e.fromNode);if(!e.columns.length||!e.values.length)return {sql:o,bindings:[]};let n=[],s=e.columns.map((a,l)=>{let u=e.values[l];return u instanceof I?`${r.formatStringColumn("sqlite",a)} = ${u.rawValue}`:(n.push(u),`${r.formatStringColumn("sqlite",a)} = ?`)}).join(", ");return {sql:`${o} set ${s}`,bindings:n}}},ty=new $l;var Dl=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:e.value??[]};let r="",o=[];if(this.isRawNode(e.value)){let n=this.formatRawIdentifierIfPossible(e.value.rawValue);r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ${n}`,o=[];}else if(Array.isArray(e.value))if(e.operator.toLowerCase()==="between")r=`${new h(this.model).formatStringColumn("sqlite",e.column)} between ? AND ?`,o=e.value;else {let n=e.value.map(s=>"?").join(", ");r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} (${n})`,o=e.value;}else if(e.operator.includes("null"))r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator}`,o=[];else {if(e.value===void 0)return {sql:"",bindings:[]};r=`${new h(this.model).formatStringColumn("sqlite",e.column)} ${e.operator} ?`,o=[e.value];}return e.isNegated&&(r=`not (${r})`),{sql:r.trim(),bindings:o}}isRawNode(t){return t&&typeof t=="object"&&"rawValue"in t&&t.isRawValue===true}formatRawIdentifierIfPossible(t){return /^[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?$/.test(t)?new h(this.model).formatStringColumn("sqlite",t):t}},ry=new Dl;var Il=class{toSql(t){let e=t;if(!e.nodes||e.nodes.length===0)return {sql:"",bindings:[]};let r=new N(this.model,"sqlite"),{sql:o,bindings:n}=r.parse(e.nodes,e.currParamIndex,true);return {sql:`(${o})`,bindings:n}}},oy=new Il;var El=class{toSql(t){let e=t;if(e.isRawValue)return {sql:e.column,bindings:[]};let r="",o=[],n=new h(this.model).formatStringColumn("sqlite",e.column);switch(e.jsonOperator){case "=":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "not contains":r=`json(${n}) = json(?)`,o=[JSON.stringify(e.value)];break;case "raw":r=e.column,o=Array.isArray(e.value)?e.value:[];break}return e.isNegated&&(r=`NOT (${r})`),{sql:r.trim(),bindings:o}}},ny=new El;var Pl=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 N(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 N(this.model,"sqlite"),{sql:r,bindings:o}=e.parse([t.subquery],t.currParamIndex);return {sql:`${t.column} ${t.operator} (${r})`.trim(),bindings:o}}},sy=new Pl;var vl=class{toSql(t){let e=t,r=new N(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}}},iy=new vl;var ay={mssql:{alter_table:{add_column:Iu,add_constraint:Eu,add_primary_key:Pu,alter_column_type:vu,alter_table:Bu,drop_column:Qu,drop_constraint:Ku,drop_default:ku,drop_not_null:Fu,drop_primary_key:Uu,rename_column:Vu,rename_table:Ju,set_default:Hu,set_not_null:zu,set_table_options:Yu},column:{column_type:Gu},constraint:{after:Zu,constraint:Xu},create_table:{create_table:ed},delete:{delete:td},distinct:{distinct:rd,distinct_on:od},drop_table:{drop_table:nd},extension:{create_extension:sd},from:{from:id},group_by:{group_by:ad},having:{having:ld},index_op:{create_index:ud,drop_index:dd},insert:{insert:md},join:{join:cd},limit:{limit:pd},lock:{lock:fd},offset:{offset:yd},on_duplicate:{on_duplicate:hd},order_by:{order_by:gd},raw:{raw:bd},schema:{check_constraint_info:Td,foreign_key_info:Nd,get_column_listing:wd,get_tables:Sd,has_check_constraint:Cd,has_column:qd,has_index:_d,has_primary_key:Rd,has_table:Md,index_info:Ad,primary_key_info:Od,table_info:xd},select:{select:$d,select_json:Dd},truncate:{truncate:Id},union:{union:Ed},update:{update:Pd},where:{where:vd,where_group:Bd,where_json:Qd,where_subquery:Kd},with:{with:kd}},mysql:{alter_table:{add_column:Ld,add_constraint:Wd,add_primary_key:jd,alter_column_type:Fd,alter_table:Ud,drop_column:Vd,drop_constraint:Jd,drop_default:Hd,drop_not_null:zd,drop_primary_key:Yd,rename_column:Gd,rename_table:Zd,set_default:Xd,set_not_null:em,set_table_options:tm},column:{column_type:rm},constraint:{after:om,constraint:nm},create_table:{create_table:sm},delete:{delete:im},distinct:{distinct:am,distinct_on:lm},drop_table:{drop_table:um},extension:{create_extension:dm},from:{from:mm},group_by:{group_by:cm},having:{having:pm},index_op:{create_index:fm,drop_index:ym},insert:{insert:hm},join:{join:gm},limit:{limit:bm},lock:{lock:Tm},offset:{offset:Nm},on_duplicate:{on_duplicate:wm},order_by:{order_by:Sm},raw:{raw:Cm},schema:{check_constraint_info:qm,foreign_key_info:_m,get_column_listing:Rm,get_tables:Mm,has_check_constraint:Am,has_column:Om,has_index:xm,has_primary_key:$m,has_table:Dm,index_info:Im,primary_key_info:Em,table_info:Pm},select:{select:vm,select_json:Bm},truncate:{truncate:Qm},union:{union:Km},update:{update:km},where:{where:Lm,where_group:Wm,where_json:jm,where_subquery:Fm},with:{with:Um}},oracledb:{alter_table:{add_column:Vm,add_constraint:Jm,add_primary_key:Hm,alter_column_type:zm,alter_table:Ym,drop_column:Gm,drop_constraint:Zm,drop_default:Xm,drop_not_null:ec,drop_primary_key:tc,rename_column:rc,rename_table:oc,set_default:nc,set_not_null:sc,set_table_options:ic},column:{column_type:ac},constraint:{after:lc,constraint:uc},create_table:{create_table:dc},delete:{delete:mc},distinct:{distinct:cc,distinct_on:pc},drop_table:{drop_table:fc},extension:{create_extension:yc},from:{from:hc},group_by:{group_by:gc},having:{having:bc},index_op:{create_index:Tc,drop_index:Nc},insert:{insert:wc},join:{join:Sc},limit:{limit:Cc},lock:{lock:qc},offset:{offset:_c},on_duplicate:{on_duplicate:Rc},order_by:{order_by:Mc},raw:{raw:Ac},schema:{check_constraint_info:Oc,foreign_key_info:xc,get_column_listing:$c,get_tables:Dc,has_check_constraint:Ic,has_column:Ec,has_index:Pc,has_primary_key:vc,has_table:Bc,index_info:Qc,primary_key_info:Kc,table_info:kc},select:{select:Lc,select_json:Wc},truncate:{truncate:jc},union:{union:Fc},update:{update:Uc},where:{where:Vc,where_group:Jc,where_json:Hc,where_subquery:zc},with:{with:Yc}},postgres:{alter_table:{add_column:Gc,add_constraint:Zc,add_primary_key:Xc,alter_column_type:ep,alter_table:tp,drop_column:rp,drop_constraint:op,drop_default:np,drop_not_null:sp,drop_primary_key:ip,rename_column:ap,rename_table:lp,set_default:up,set_not_null:dp,set_table_options:mp},column:{column_type:cp},constraint:{after:pp,constraint:fp},create_table:{create_table:yp},delete:{delete:hp},distinct:{distinct:gp,distinct_on:bp},drop_table:{drop_table:Tp},extension:{create_extension:Np},from:{from:wp},group_by:{group_by:Sp},having:{having:Cp},index_op:{create_index:qp,drop_index:_p},insert:{insert:Rp},join:{join:Mp},limit:{limit:Ap},lock:{lock:Op},offset:{offset:xp},on_duplicate:{on_duplicate:$p},order_by:{order_by:Dp},raw:{raw:Ip},schema:{check_constraint_info:Ep,foreign_key_info:Pp,get_column_listing:vp,get_tables:Bp,has_check_constraint:Qp,has_column:Kp,has_index:kp,has_primary_key:Lp,has_table:Wp,index_info:jp,primary_key_info:Fp,table_info:Up},select:{select:Vp,select_json:Jp},truncate:{truncate:Hp},union:{union:zp},update:{update:Yp},where:{where:Gp,where_group:Zp,where_json:Xp,where_subquery:ef},with:{with:tf}},sqlite:{alter_table:{add_column:rf,add_constraint:of,alter_column_type:nf,alter_table:sf,drop_column:af,drop_constraint:lf,drop_default:uf,drop_not_null:df,drop_primary_key:mf,rename_column:cf,rename_table:pf,set_default:ff,set_not_null:yf,set_table_options:hf},column:{column_type:gf},constraint:{after:bf,constraint:Tf},create_table:{create_table:Nf},delete:{delete:wf},distinct:{distinct:Sf,distinct_on:Cf},drop_table:{drop_table:qf},extension:{create_extension:_f},from:{from:Rf},group_by:{group_by:Mf},having:{having:Af},index_op:{create_index:Of,drop_index:xf},insert:{insert:$f},join:{join:Df},limit:{limit:If},lock:{lock:Ef},offset:{offset:Pf},on_duplicate:{on_duplicate:vf},order_by:{order_by:Bf},raw:{raw:Qf},schema:{check_constraint_info:Kf,foreign_key_info:kf,get_column_listing:Lf,get_tables:Wf,has_check_constraint:jf,has_column:Ff,has_index:Uf,has_primary_key:Vf,has_table:Jf,index_info:Hf,primary_key_info:zf,table_info:Yf},select:{select:Gf,select_json:Zf},truncate:{truncate:Xf},union:{union:ey},update:{update:ty},where:{where:ry,where_group:oy,where_json:ny,where_subquery:sy},with:{with:iy}}};var N=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(q=>!!q&&q.folder==="distinctOn"),n=!o&&t.find(q=>!!q&&q.folder==="distinct"),s=this.dbType==="mssql"?t.find(q=>!!q&&q.folder==="lock")??null:null,a=s?this.getMssqlTableHints(s):"",l=t.filter(q=>q!==null&&q.folder!=="distinct"&&q.folder!=="distinctOn"),u=l.some(q=>q.folder==="offset"),d=l.some(q=>q.folder==="order_by"),m=l.find(q=>q.folder==="limit"),c=l.find(q=>q.folder==="offset"),p=this.dbType==="mssql"&&m&&!u&&!d,f=this.dbType==="mssql"&&!p&&(m||c),y=this.dbType==="oracledb"&&(m||c),T=[],b=[],C=null;p&&m&&b.push(m.limit);for(let q=0;q<l.length;q++){let O=l[q];if(p&&O.folder==="limit"||f&&(O.folder==="limit"||O.folder==="offset")||y&&(O.folder==="limit"||O.folder==="offset"))continue;O.currParamIndex=e+b.length;let D=ay[this.mapCommonDbType(this.dbType)][O.folder][O.file];if(!D)throw new Error(`Interpreter not found for ${this.dbType} ${O.keyword}`);D.model=this.model;let _=D.toSql(O);if(!_.sql||!_.sql.trim().length)continue;let v=l[q+1],$=!v||v.keyword!==O.keyword?"":v.chainsWith;if(O.folder==="lock"||O.folder==="on_duplicate"||O.folder==="schema"){T.push(`${_.sql}${$}`),b.push(..._.bindings),C=O.keyword;continue}if(C!==O.keyword||O.canKeywordBeSeenMultipleTimes){if(r)T.push(`${_.sql}${$}`);else {let V=O.keyword;if(O.folder==="with"&&this.dbType!=="mssql"){let X=q,xe=false;for(;X<l.length&&l[X].keyword===O.keyword;){let qe=l[X];if(qe.folder==="with"&&qe.clause==="recursive"){xe=true;break}X++;}xe&&(V=`${V} recursive`);}if(V==="select"){let X=p?`top (@${e}) `:"";if(o){let xe=Array.isArray(o.columns)?o.columns.join(", "):"";T.push(`select ${X}distinct on (${xe}) ${_.sql}${$}`);}else n?T.push(`select ${X}distinct ${_.sql}${$}`):T.push(`select ${X}${_.sql}${$}`);}else V==="from"&&a?T.push(`${V} ${_.sql}${a}${$}`):T.push(`${V} ${_.sql}${$}`);}C=O.keyword;}else T.push(`${_.sql}${$}`);b.push(..._.bindings);}if(f){d||T.push("order by (select null)");let q=c?.offset??0;b.push(q);let D=`offset @${e+b.length-1} rows`;if(m){b.push(m.limit);let _=e+b.length-1;D+=` fetch next @${_} rows only`;}T.push(D);}if(y){d||T.push("order by null");let q=c?.offset??0;b.push(q);let D=`offset :${e+b.length-1} rows`;if(m){b.push(m.limit);let _=e+b.length-1;D+=` fetch next :${_} rows only`;}T.push(D);}return {sql:T.join(" "),bindings:b}}mapCommonDbType(t){switch(t){case "mariadb":return "mysql";case "cockroachdb":return "postgres";default:return t}}getMssqlTableHints(t){let e=[];switch(t.lockType){case "UPDATE":e.push("UPDLOCK");break;case "SHARE":e.push("HOLDLOCK");break;case "NO_KEY_UPDATE":e.push("UPDLOCK");break;case "KEY_SHARE":e.push("HOLDLOCK");break}return t.skipLocked&&e.push("READPAST"),t.noWait&&e.push("NOWAIT"),e.length>0?` with (${e.join(", ")})`:""}};var vh=i=>{if(i==null||typeof i!="object"||i instanceof Date)return false;if(Array.isArray(i))return true;let t=Object.getPrototypeOf(i);return t===Object.prototype||t===null},h=class{constructor(t){this.model=t;this.modelColumnsMap=typeof t.getColumnsByName=="function"?t.getColumnsByName():new Map;let e=[],r=[];for(let o of this.modelColumnsMap.values())(o.prepare||o.autoUpdate)&&e.push(o),o.autoUpdate&&r.push(o);this.autoInsertColumns=e,this.autoUpdateColumns=r;}formatStringColumn(t,e){if(e==="*")return "*";if(e.includes(".")){let[n,s]=e.split(".");if(s==="*")switch(t){case "mysql":case "mariadb":return `\`${n}\`.*`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}".*`;case "mssql":return `[${n}].*`;default:throw new Error(`Unsupported database type: ${t}`)}let a=this.modelColumnsMap.get(s)?.databaseName??J(s,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${n}\`.\`${a}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${n}"."${a}"`;case "mssql":return `[${n}].[${a}]`;default:throw new Error(`Unsupported database type: ${t}`)}}let o=this.modelColumnsMap.get(e)?.databaseName??J(e,this.model.databaseCaseConvention);switch(t){case "mysql":case "mariadb":return `\`${o}\``;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${o}"`;case "mssql":return `[${o}]`;default:throw new Error(`Unsupported database type: ${t}`)}}formatStringColumnBare(t,e){let r=e.includes(".")?e.split(".")[1]:e;return this.formatStringColumn(t,r)}formatStringTable(t,e){e=e.replace(/\s+/g," ").trim();let r="";switch(e.toLowerCase().includes(" as ")&&([e,r]=e.split(" as ")),t){case "mysql":case "mariadb":return `\`${e}\`${r?` as \`${r}\``:""}`;case "postgres":case "cockroachdb":case "sqlite":case "oracledb":return `"${e}"${r?` as "${r}"`:""}`;case "mssql":return `[${e}]${r?` as [${r}]`:""}`;default:return `${e}${r?` as ${r}`:""}`}}async prepareColumns(t,e,r="insert"){if(!t.length)return {columns:t,values:e};let o=[],n=[];for(let d=0;d<t.length;d++){let m=t[d],c=e[d];m!=="*"&&(o.push(m),n.push(c));}let s=new Set(o),a=null;for(let d=0;d<o.length;d++){let m=o[d],c=n[d],p=this.modelColumnsMap.get(m);if(p){if(p.prepare){let f=r==="insert"?p.prepare(c):p.prepare(c)??c;f!==null&&typeof f?.then=="function"?(a||(a=[]),a.push({index:d,promise:f})):n[d]=f;}}else vh(c)&&(n[d]=JSON.stringify(c));}if(a){let d=await Promise.all(a.map(m=>m.promise));for(let m=0;m<a.length;m++)n[a[m].index]=d[m];}let l=this.model.primaryKey,u=r==="insert"?this.autoInsertColumns:this.autoUpdateColumns;for(let d of u){let m=d.columnName;if(s.has(m)||r==="insert"&&m===l&&!d.prepare)continue;o.push(m);let c=d.prepare?await d.prepare(void 0):void 0;n.push(c??void 0);}return {columns:o,values:n}}getFromForWriteOperations(t,e){if(typeof e.table=="string")return this.formatStringTable(t,e.table);let r=new N(this.model,t);return Array.isArray(e.table)?`(${r.parse(e.table).sql})`:`(${r.parse([e.table]).sql})`}};var rt=class extends w{constructor(e,r=false,o){super("delete from",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="delete";this.file="delete";this.fromNode=e,this.returning=o;}};var U=class extends w{constructor(e,r){super("from");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="from";this.file="from";this.table=e,this.alias=r;}};var G=class extends w{constructor(e,r=[],o,n=false,s=false){super("insert into",s);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="insert";this.file="insert";this.fromNode=e,this.records=r,this.returning=o,this.disableReturning=n;}};var he=class extends w{constructor(e,r,o,n="update",s,a=false){super("on duplicate",a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="on_duplicate";this.file="on_duplicate";this.table=e,this.conflictColumns=r,this.columnsToUpdate=o,this.mode=n,this.returning=s;}};var Me=class extends w{constructor(e,r=[],o=[],n=false,s){super("update",n);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="update";this.file="update";this.fromNode=e,this.columns=r,this.values=o,this.returning=s;}};var ly;ly=Symbol.toStringTag;var Z=class{constructor(t,e,r,o){this.unWrapFn=t;this.toSqlFn=e;this.toQueryFn=r;this.executor=o;this[ly]="WriteOperation";}then(t,e){return this.executor().then(t,e)}catch(t){return this.executor().catch(t)}finally(t){return this.executor().finally(t)}toQuery(){return this.toQueryFn()}toSql(){return this.toSqlFn()}unWrap(){return this.unWrapFn()}};var Bh=async(i,t,e,r,o,n=false)=>{let s=Object.create(t.prototype),a=null;for(let l of Object.keys(i)){let u=i[l],d=r.get(l)?.columnName??l,m=e.has(d),c=n?true:o?o.has(d):true;if(m){if(!c)continue;if(u===null){s[d]=null;continue}let p=e.get(d);if(p?.serialize){let f=p.serialize(u);f!==null&&typeof f?.then=="function"?(a||(a=[]),a.push({key:d,promise:f})):s[d]=f;continue}s[d]=u;continue}(!n||o&&o.has(d))&&(s[d]=u);}if(a){let l=await Promise.all(a.map(u=>u.promise));for(let u=0;u<a.length;u++)s[a[u].key]=l[u];}if(o)for(let l of o)l in s||(s[l]=null);return s},Ae=async(i,t,e=[])=>{if(!i.length)return null;let r=t.getColumnsByName(),o=t.getColumnsByDatabaseName(),n=e.some(u=>u.includes("*")),s=[];for(let u of e){if(u.toLowerCase().includes(" as ")){let p=u.match(/\s+as\s+(.+)$/i);p&&s.push(p[1].trim());continue}let m=u;if(m.includes(".")&&(m=m.split(".").pop()),m==="*")continue;let c=r.get(m)?.columnName??m;s.push(c);}let a=s.length?new Set(s):null,l=await Promise.all(i.map(u=>Bh(u,t,r,o,a,n)));return l.length===1?l[0]:l};var k=class extends Error{constructor(t){super(""),this.message=`Driver '${t}' not found, it's likely not installed, try running 'npm install ${t}'`;}};var Qh=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,Kh=/^\d{4}-\d{2}-\d{2}$/,Bl=i=>typeof i!="string"?i:Qh.test(i)?new Date(i.replace(" ","T")+"Z"):Kh.test(i)?new Date(i+"T00:00:00Z"):i,kh=async i=>new Promise((t,e)=>{if(i.type===2017){let o="";i.setEncoding("utf8"),i.on("data",n=>{o+=n;}),i.on("end",()=>t(o)),i.on("error",e);}else {let o=[];i.on("data",n=>{o.push(n);}),i.on("end",()=>t(Buffer.concat(o))),i.on("error",e);}}),uy=async i=>{let t={};for(let e in i){let r=i[e];r&&typeof r=="object"&&r.constructor?.name==="Lob"?t[e]=await kh(r):t[e]=r;}return t};var Ht=class extends stream.Readable{constructor(t,e,r=[],o){super({objectMode:true}),this.db=t,this.query=e,this.params=r,this.started=false,this.events=o;}_read(){this.started||(this.started=true,this.readRows());}readRows(){let t=0,e=false,r=false;this.db.each(this.query,this.params,(o,n)=>{if(o){r=true,this.emit("error",o);return}t++;let s=false,a,l={write:u=>{s=true,a=u;}};Promise.resolve(this.events.onData?.(l,n)).then(()=>{if(!r){if(s){this.push(a);return}this.push(n);}}).catch(u=>{r=true,this.emit("error",u);}).finally(()=>{t--,e&&t===0&&!r&&this.push(null);});},o=>{if(o){r=true,this.emit("error",o);return}e=true,t===0&&!r&&this.push(null);});}},dy=(i,t,e,r)=>{let o=["begin","begin transaction","commit","rollback"].includes(i.trim().toLowerCase()),n=r.customConnection??e.getPool();if(o)return new Promise((u,d)=>{n.run(i,t,function(m){m&&d(m),u(this.changes);});});if(r.mode==="fetch")return new Promise((u,d)=>{n.all(i,t,(m,c)=>{m&&d(m),(!c||!c.length)&&u([]),u(c);});});let s=r?.typeofModel;if(!s)return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});});let a=s.primaryKey,l=s.table;if(r.mode==="insertOne"||r.mode==="insertMany"){if(r.mode==="insertOne")return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);let f=r.models&&Array.isArray(r.models)&&r.models.length?r.models[0]:null;if(!a){m([f]);return}let y=f?.[a]||this.lastID;if(!y)return c(new g("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let T=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get(T,[y],(b,C)=>{if(b)return c(b);m([C]);});});});if(!Array.isArray(r.models))throw new g("SqlRunnerUtils::massiveInsert models should be an array, report to the maintainers.","DEVELOPMENT_ERROR");let u=r.models;if(!a)return new Promise((m,c)=>{n.run(i,t,function(p){if(p)return c(p);m(u);});});let d=[];return new Promise(async(m,c)=>{try{let p=u.map(async f=>{let y=new h(s),{columns:T,values:b}=await y.prepareColumns(Object.keys(f),Object.values(f),"insert"),C=Object.fromEntries(T.map((D,_)=>[D,b[_]])),A=new N(s,e.getDbType()),{sql:q,bindings:O}=A.parse([new G(new U(s.table),[C])]);return new Promise((D,_)=>{n.run(q,O,function(v){if(v)return _(v);let W=f[a]||this.lastID;if(!W)return _(new g("SqlRunnerUtils::promisifySqliteQuery","MODEL_HAS_NO_PRIMARY_KEY"));let $=`SELECT * FROM ${l} WHERE ${a} = ?`;n.get($,[W],(V,X)=>{if(V)return _(V);D(X);});});})});d=await Promise.all(p),m(d);}catch(p){c(p);}})}return new Promise((u,d)=>{n.run(i,t,function(m){m?d(new Error(m.message)):u(this.changes);});})};var ot=class{constructor(t){this.observers=t??[];}add(t){this.observers.push(t);}async notifyBefore(t){for(let e of this.observers)e?.onBeforeQuery&&await e.onBeforeQuery(t);}async notifyAfter(t,e){for(let r of this.observers)r?.onAfterQuery&&(t.result??(t.result=e),await r.onAfterQuery(t));}async notifyError(t){for(let e of this.observers)e?.onQueryError&&await e.onQueryError(t);}},my=i=>{if(!i)return "OTHER";let t=i.trim().toUpperCase();return t.startsWith("SELECT")?"SELECT":t.startsWith("INSERT")?"INSERT":t.startsWith("UPDATE")?"UPDATE":t.startsWith("DELETE")?"DELETE":"OTHER"};function bt(i){let t=perf_hooks.performance.now()-i;return Math.round(t*100)/100}var z=async(i,t,e,r,o="rows",n)=>{await e.ensureConnected();let s={id:Re.randomUUID(),sql:i,params:t,model:void 0,operation:my(i),timestamp:perf_hooks.performance.now()};try{let l=e.observerChain;l&&typeof l.notifyBefore=="function"&&await l.notifyBefore(s);}catch{}n?.shouldNotLog||te(i,e.logs,t,e.inputDetails.queryFormatOptions,r);let a=perf_hooks.performance.now();switch(r){case "mysql":case "mariadb":let l=e.sqlConnection??e.getPool(),u=await Tt(()=>l.query(i,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let W=bt(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:W,result:u};await $.notifyAfter(V);}}catch{}return o==="affectedRows"?u[0].affectedRows:o==="raw"?u:u[0];case "postgres":case "cockroachdb":let d=e.sqlConnection??e.getPool(),m=0,c=i.replace(/\?/g,()=>`$${++m}`),p=await Tt(()=>d.query(c,t),e.inputDetails.connectionPolicies?.retry,e.logs);try{let W=bt(a),$=e.observerChain;if($&&typeof $.notifyAfter=="function"){let V={...s,duration:W,result:p};await $.notifyAfter(V);}}catch{}return o==="rows"?p.rows:o==="raw"?p:p.rowCount;case "sqlite":let f=await Tt(()=>dy(i,t,e,{typeofModel:n?.sqlLiteOptions?.typeofModel,mode:n?.sqlLiteOptions?.mode||"fetch",models:n?.sqlLiteOptions?.models}),e.inputDetails.connectionPolicies?.retry,e.logs),y=bt(a);try{let W=e.observerChain;if(W&&typeof W.notifyAfter=="function"){let $={...s,duration:y,result:f};await W.notifyAfter($);}}catch{}return o==="raw"?Array.isArray(f)?f:[f]:f;case "mssql":let T=e.getPool(),b=e.sqlConnection?e.sqlConnection.request():T.request();t.forEach((W,$)=>{b.input(`p${$}`,W);});let C=0,A=i.replace(/\?|@(\d+)/g,()=>`@p${C++}`),q=await Tt(()=>b.query(A),e.inputDetails.connectionPolicies?.retry,e.logs),O=bt(a);try{let W=e.observerChain;if(W&&typeof W.notifyAfter=="function"){let $={...s,duration:O,result:q};await W.notifyAfter($);}}catch{}return o==="affectedRows"?q.rowsAffected[0]:o==="raw"?q:q.recordset;case "oracledb":let D=4002,_=null,v=!!e.sqlConnection;try{_=e.sqlConnection?e.sqlConnection:await e.getConnection();let W=t.map(Bl),$=0,V=i.replace(/\?/g,()=>`:${++$}`),X=await Tt(()=>_.execute(V,W,{outFormat:D,autoCommit:!v}),e.inputDetails.connectionPolicies?.retry,e.logs),xe=bt(a);try{let yt=e.observerChain;if(yt&&typeof yt.notifyAfter=="function"){let vt={...s,duration:xe,result:X};await yt.notifyAfter(vt);}}catch{}return o==="affectedRows"?X.rowsAffected:o==="raw"?X:await Promise.all(X.rows?.map(async yt=>{let vt=await uy(yt),tu={};for(let ru in vt)tu[ru.toLowerCase()]=vt[ru];return tu})??[])}finally{_&&!v&&await _.close();}default:throw new g("ExecSql",`UNSUPPORTED_DATABASE_TYPE_${r}`)}},Yt=async(i,t,e,r={},o)=>{let n=e.type;switch(n){case "mariadb":case "mysql":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),d=a.connection.query(i,t).stream({highWaterMark:r.highWaterMark,objectMode:r.objectMode??true}),m=0,c=false,p=false,f=()=>{try{a.release();}catch{}};return d.on("data",y=>{if(o.onData){m++,Promise.resolve(o.onData(l,y)).then(()=>{m--,c&&m===0&&!p&&(f(),l.end());}).catch(T=>{p=true,f(),l.destroy(T);});return}l.write(y);}),d.on("end",()=>{c=true,m===0&&!p&&(f(),l.end());}),d.on("error",y=>{p=true,f(),l.destroy(y);}),l.on("close",()=>{f();}),l}case "cockroachdb":case "postgres":{let s=e.getPool(),a=e.sqlConnection,l=!a,u=a??await s.connect(),d=await import('pg-query-stream').catch(()=>{throw new k("pg-query-stream")}),m=new stream.PassThrough({objectMode:r.objectMode||true,highWaterMark:r.highWaterMark}),c=0,p=i.replace(/\?/g,()=>`$${++c}`),f=new d.default(p,t,{highWaterMark:r.highWaterMark,rowMode:r.rowMode,batchSize:r.batchSize,types:r.types}),y=u.query(f),T=0,b=false,C=false,A=q=>{if(l)try{u.release(q);}catch{}};return y.on("data",q=>{if(o.onData){T++,Promise.resolve(o.onData(m,q)).then(()=>{T--,b&&T===0&&!C&&(A(),m.end());}).catch(O=>{C=true,A(O),m.destroy(O);});return}m.write(q);}),y.on("end",()=>{b=true,T===0&&!C&&(A(),m.end());}),y.on("error",q=>{C=true,A(q),m.destroy(q);}),m}case "sqlite":{let s=e.sqlConnection??e.getPool();return new Ht(s,i,t,{onData:o.onData})}case "mssql":{let s=e.sqlConnection??e.getPool(),a=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),l=s.request();l.stream=true,t.forEach((f,y)=>{l.input(`p${y}`,f);});let u=0,d=i.replace(/\?|@(\d+)/g,()=>`@p${u++}`),m=0,c=false,p=false;return l.on("row",f=>{if(!p){if(o.onData){m++,Promise.resolve(o.onData(a,f)).then(()=>{m--,c&&m===0&&!p&&a.end();}).catch(y=>{p=true,a.destroy(y);});return}a.write(f);}}),l.on("error",f=>{p=true,a.destroy(f);}),l.on("done",()=>{c=true,m===0&&!p&&a.end();}),l.query(d),a}case "oracledb":{let s=e.getPool(),a=e.sqlConnection??await s.getConnection(),l=new stream.PassThrough({objectMode:r.objectMode??true,highWaterMark:r.highWaterMark}),u=4002,d=0,m=i.replace(/\?/g,()=>`:${++d}`),c=t.map(Bl),p=a.queryStream(m,c,{outFormat:u}),f=0,y=false,T=false,b=async()=>{try{await a.close();}catch{}};return p.on("data",C=>{if(T)return;let A={};for(let q in C)A[q.toLowerCase()]=C[q];if(o.onData){f++,Promise.resolve(o.onData(l,A)).then(()=>{f--,y&&f===0&&!T&&(b(),l.end());}).catch(q=>{T=true,b(),l.destroy(q);});return}l.write(A);}),p.on("end",()=>{y=true,f===0&&!T&&(b(),l.end());}),p.on("error",C=>{T=true,b(),l.destroy(C);}),l}default:throw new g("ExecSqlStreaming",`UNSUPPORTED_DATABASE_TYPE_${n}`)}};async function Tt(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++,ju(`Retrying sql in ${n}ms (attempt ${r}/${o})`,"info",e),await new Promise(l=>setTimeout(l,n)),s();throw a}}return s()}function cy(){return {}}var Le=class{constructor(t,e){this.replicationMode=null;this.model=t,this.modelInstance=cy(),this.sqlDataSource=e,this.logs=this.sqlDataSource.logs,this.sqlType=this.sqlDataSource.getDbType(),this.astParser=new N(this.model,this.sqlType),this.interpreterUtils=new h(this.model);}setReplicationMode(t){return this.replicationMode=t,this}async find(t){if(!t)return this.query().many();let e=this.query();return t.select&&e.select(...t.select),t.relations&&t.relations.forEach(r=>{e.load(r);}),t.where&&this.handleWhereCondition(e,t.where),t.orderBy&&Object.entries(t.orderBy).forEach(([r,o])=>{e.orderBy(r,o);}),t.limit&&e.limit(t.limit),t.offset&&e.offset(t.offset),t.groupBy&&e.groupBy(...t.groupBy),e.many({ignoreHooks:t.ignoreHooks||[]})}async findOne(t){let e=await this.find({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset,limit:1});return e.length?e[0]:null}async findOneOrFail(t){let e=await this.findOne({groupBy:t.groupBy,orderBy:t.orderBy,relations:t.relations,select:t.select,where:t.where,ignoreHooks:t.ignoreHooks,offset:t.offset});if(e===null)throw t.customError?t.customError:new g(this.model.name+"::findOneOrFail","ROW_NOT_FOUND");return e}async findOneByPrimaryKey(t,e){if(!this.model.primaryKey)throw new g(this.model.name+"::findOneByPrimaryKey","MODEL_HAS_NO_PRIMARY_KEY");return this.query().select(...e||[]).where(this.model.primaryKey,t).one({ignoreHooks:["afterFetch","beforeFetch"]})}insert(t,e={}){let r=Object.fromEntries(Object.keys(t).map(u=>[u,t[u]])),o=!e.returning||e.returning.length===0,n=new G(new U(this.model.table),[r],e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new Z(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(C){throw C}e.ignoreHooks||await this.model.beforeInsert?.(t);let{columns:u,values:d}=await this.interpreterUtils.prepareColumns(Object.keys(t),Object.values(t),"insert"),m={};u.forEach((C,A)=>{let q=d[A];m[C]=q,t[C]??(t[C]=q);});let c=!e.returning||e.returning.length===0,{sql:p,bindings:f}=this.astParser.parse([new G(new U(this.model.table),[m],e.returning,c)]),y=await z(p,f,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[t]}});if(c)return;if(this.sqlType==="mysql"||this.sqlType==="mariadb")return this.handleMysqlInsert(y,[t],"one",e.returning);let T=y[0];return T?(await this.model.afterFetch?.([T]),await Ae([T],this.model,e.returning)):t})}insertMany(t,e={}){let r=t.map(u=>Object.fromEntries(Object.keys(u).map(d=>[d,u[d]]))),o=!e.returning||e.returning.length===0,n=new G(new U(this.model.table),r,e.returning,o),s=()=>{let u=this.astParser.parse([n]);return {sql:u.sql,bindings:u.bindings}},a=()=>{let u=this.astParser.parse([n]);return {sql:Xe(this.sqlDataSource,u.sql),bindings:u.bindings}},l=()=>{let{sql:u,bindings:d}=a();return Ge(u,d)};return new Z(s,a,l,async()=>{try{await this.model.validate?.(t);}catch(T){throw T}if(await this.model.beforeInsertMany?.(t),this.sqlType==="oracledb"){let T=this.model.primaryKey,b=Object.keys(t[0]||{});if(T&&!b.includes(T))return this.handleOracleIdentityInsert(t,e)}let u=new Array(t.length);await Promise.all(t.map(async(T,b)=>{let{columns:C,values:A}=await this.interpreterUtils.prepareColumns(Object.keys(T),Object.values(T),"insert"),q={};C.forEach((O,D)=>{let _=A[D];q[O]=_,T[O]??(T[O]=_);}),u[b]=q;}));let d=!e.returning||e.returning.length===0,{sql:m,bindings:c}=this.astParser.parse([new G(new U(this.model.table),u,e.returning,d)]),p=await z(m,c,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:t}});if(d)return [];if(this.sqlType==="mysql"||this.sqlType==="mariadb")return await this.handleMysqlInsert(p,t,"many",e.returning)||[];let f=p;return f.length?(await this.model.afterFetch?.(f),await Ae(f,this.model,e.returning)||[]):[]})}upsertMany(t,e,r,o={updateOnConflict:true}){let n=r.map(c=>Object.fromEntries(Object.keys(c).map(p=>[p,c[p]]))),s=new G(new U(this.model.table),n,void 0,true),a=o.returning?.length&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0;new he(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",a);let u=()=>{let c=this.astParser.parse([s]);return {sql:c.sql,bindings:c.bindings}},d=()=>{let c=this.astParser.parse([s]);return {sql:Xe(this.sqlDataSource,c.sql),bindings:c.bindings}},m=()=>{let{sql:c,bindings:p}=d();return Ge(c,p)};return new Z(u,d,m,async()=>{let c=[];if(await this.model.beforeInsertMany?.(r),await Promise.all(r.map(async O=>{let{columns:D,values:_}=await this.interpreterUtils.prepareColumns(Object.keys(O),Object.values(O),"insert"),v=Object.fromEntries(D.map((W,$)=>[W,_[$]]));c.push(v);})),this.sqlType==="mssql")return this.executeMssqlMerge(c,t,e,o,r);let p=!o.returning||o.returning.length===0,f=!p&&(this.sqlType==="postgres"||this.sqlType==="cockroachdb")?o.returning:void 0,{sql:y,bindings:T}=this.astParser.parse([new G(new U(this.model.table),c,void 0,true),new he(this.model.table,t,e,o.updateOnConflict??true?"update":"ignore",f)]),b=await z(y,T,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:r}});if(p)return [];if(this.sqlType==="postgres"||this.sqlType==="cockroachdb"){if(b.length<r.length&&!(o.updateOnConflict??true)){let _=t[0],v=r.map($=>$[_]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(_,v).many()}let O=b;return await this.model.afterFetch?.(O),await Ae(O,this.model,o.returning)||[]}let C=t[0],A=r.map(O=>O[C]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(C,A).many()})}async executeMssqlMerge(t,e,r,o,n){if(!t.length)return [];let s=Object.keys(t[0]),a=this.interpreterUtils.formatStringColumn("mssql",this.model.table),l=D=>this.interpreterUtils.formatStringColumn("mssql",D),u=[],d=t.map(D=>`select ${s.map(v=>(u.push(D[v]),`@${u.length}`)).join(", ")}`),m=s.map(l).join(", "),c=d.join(" union all "),p=e.map(D=>`target.${l(D)} = source.${l(D)}`).join(" and "),f=r.filter(D=>!e.includes(D)).map(D=>`target.${l(D)} = source.${l(D)}`).join(", "),y=s.map(l).join(", "),T=s.map(D=>`source.${l(D)}`).join(", "),b=o.returning&&o.returning.length?o.returning.map(D=>`inserted.${l(D)}`).join(", "):s.map(D=>`inserted.${l(D)}`).join(", "),A=(o.updateOnConflict??true)&&f?`when matched then update set ${f}`:"",q=`merge into ${a} as target using (${c}) as source (${m}) on ${p} ${A} when not matched then insert (${y}) values (${T}) output ${b};`,O=await z(q,u,this.sqlDataSource,this.sqlType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:n}});if(O.length===0&&!(o.updateOnConflict??true)){let D=e[0],_=n.map(W=>W[D]);return await this.query().select(...o.returning?.length?o.returning:["*"]).whereIn(D,_).many()}return O}async updateRecord(t,e,r){let o=new Set(this.model.getColumns().map(f=>f.columnName)),n=Object.keys(e).filter(f=>o.has(f)),s=n.map(f=>e[f]),{columns:a,values:l}=await this.interpreterUtils.prepareColumns(n,s,"update"),{primaryKey:u}=this.model;if(!u)throw new g(this.model.name+"::updateRecord","MODEL_HAS_NO_PRIMARY_KEY");let d=a.indexOf(u);d!==-1&&(a.splice(d,1),l.splice(d,1));let{sql:m,bindings:c}=this.astParser.parse([new Me(new U(this.model.table),a,l),new x(u,"and",false,"=",t)]);if(await z(m,c,this.sqlDataSource,this.sqlType,"affectedRows"),!r?.returning||r.returning.length===0)return;let p=await this.findOneByPrimaryKey(t,r.returning);if(!p)throw new g(this.model.name+"::updateRecord","ROW_NOT_FOUND");return p}async deleteRecord(t){if(!this.model.primaryKey)throw new g(this.model.name+"::deleteRecord","MODEL_HAS_NO_PRIMARY_KEY");let e=new x(this.model.primaryKey,"and",false,"=",t),{sql:r,bindings:o}=this.astParser.parse([new rt(new U(this.model.table)),e]);await z(r,o,this.sqlDataSource,this.sqlType,"affectedRows");}query(){let t=new Ie(this.model,this.sqlDataSource);return this.replicationMode&&t.setReplicationMode(this.replicationMode),t}async handleMysqlInsert(t,e,r,o){if(!this.model.primaryKey){if(r==="one"){let a=e.length?e[0]:null;return a?await Ae([a],this.model):null}return await Ae(e,this.model)}if(this.model.primaryKey&&e[0][this.model.primaryKey]){let a=e.map(d=>d[this.model.primaryKey]),l=a.map(d=>`'${d}'`).join(","),u=await this.query().select(...o??["*"]).whereIn(this.model.primaryKey,a).orderByRaw(`FIELD(${this.model.primaryKey}, ${l})`).many();return r==="one"?u.length?u[0]:null:u}let n=Array.from({length:t.affectedRows},(a,l)=>l+t.insertId),s=await this.query().select(...o||["*"]).whereIn(this.model.primaryKey,n).many();return r==="one"?s.length?s[0]:null:s}async handleOracleIdentityInsert(t,e){let r=[],o=this.model.primaryKey;for(let n of t){let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(n),Object.values(n),"insert"),l={};s.forEach((p,f)=>{let y=a[f];l[p]=y,n[p]??(n[p]=y);});let{sql:u,bindings:d}=this.astParser.parse([new G(new U(this.model.table),[l],e.returning)]);await z(u,d,this.sqlDataSource,this.sqlType,"rows");let m=this.query().select(...e.returning||["*"]);for(let[p,f]of Object.entries(l))f!=null&&p!==o&&m.where(p,"=",f);o&&m.orderBy(o,"desc");let c=await m.one({ignoreHooks:["beforeFetch"]});if(c){let p=c;o&&p[o]&&(n[o]=p[o]),r.push(c);}else r.push(n);}return await this.model.afterFetch?.(r),r}handleWhereCondition(t,e,r=false){if(e)for(let[o,n]of Object.entries(e))o==="$and"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{for(let l of n)this.handleWhereCondition(a,l,false);}):o==="$or"&&Array.isArray(n)?t[r?"orWhere":"where"](a=>{let l=true;for(let u of n)this.handleWhereCondition(a,u,!l),l=false;}):this.applyFieldCondition(t,o,n,r);}applyFieldCondition(t,e,r,o=false){if(r==null||typeof r!="object"){r===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",r):t.where(e,"=",r);return}let n=r,s=n.op,a=n.value;switch(s){case "$eq":a===null?o?t.orWhereNull(e):t.whereNull(e):o?t.orWhere(e,"=",a):t.where(e,"=",a);break;case "$ne":a===null?o?t.orWhereNotNull(e):t.whereNotNull(e):o?t.orWhere(e,"!=",a):t.where(e,"!=",a);break;case "$gt":o?t.orWhere(e,">",a):t.where(e,">",a);break;case "$gte":o?t.orWhere(e,">=",a):t.where(e,">=",a);break;case "$lt":o?t.orWhere(e,"<",a):t.where(e,"<",a);break;case "$lte":o?t.orWhere(e,"<=",a):t.where(e,"<=",a);break;case "$between":{let[l,u]=a;o?t.orWhereBetween(e,l,u):t.whereBetween(e,l,u);break}case "$not between":{let[l,u]=a;o?t.orWhereNotBetween(e,l,u):t.whereNotBetween(e,l,u);break}case "$regexp":o?t.orWhereRegexp(e,a):t.whereRegexp(e,a);break;case "$not regexp":o?t.orWhereNotRegexp(e,a):t.whereNotRegexp(e,a);break;case "$is null":o?t.orWhereNull(e):t.whereNull(e);break;case "$is not null":o?t.orWhereNotNull(e):t.whereNotNull(e);break;case "$like":o?t.orWhereLike(e,a):t.whereLike(e,a);break;case "$not like":o?t.orWhereNotLike(e,a):t.whereNotLike(e,a);break;case "$ilike":o?t.orWhereILike(e,a):t.whereILike(e,a);break;case "$not ilike":o?t.orWhereNotILike(e,a):t.whereNotILike(e,a);break;case "$in":o?t.orWhereIn(e,a):t.whereIn(e,a);break;case "$nin":o?t.orWhereNotIn(e,a):t.whereNotIn(e,a);break;default:o?t.orWhere(e,"=",r):t.where(e,"=",r);}}};var Nt=class{constructor(t,e,r){this.dbType=e,this.sqlDataSource=r,this.modelRelations=Su(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 g("SqlModelManagerUtils::getRelationFromModel",`RELATION_NOT_FOUND_IN_MODEL_${t.toString()}`);return e}};function Gt(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 py(i,t){return {perPage:i,total:t,firstPage:1,isEmpty:t===0}}var nt=i=>typeof i=="number"?i:parseFloat(i);var Zt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_column";this.column=e;}};var ge=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="add_constraint";this.constraint=e;}};var st=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="add_primary_key";this.columns=e;}};var Xt=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="alter_column_type";this.column=e,this.newType=r,this.options=o;}};var de=class extends w{constructor(e,r=[],o=false){super("alter table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="alter_table";this.table=e,this.children=r,this.ifExists=o;}};var er=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_column";this.column=e;}};var be=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_constraint";this.constraintName=e;}};var wt=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_default";this.column=e;}};var tr=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="drop_not_null";this.column=e;}};var it=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="drop_primary_key";this.table=e;}};var rr=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="rename_column";this.oldName=e,this.newName=r;}};var or=class extends w{constructor(e,r){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_default";this.column=e,this.defaultValue=r;}};var nr=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="alter_table";this.file="set_not_null";this.column=e;}};var We=class extends w{constructor(e){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="alter_table";this.file="set_table_options";this.engine=e.engine,this.charset=e.charset,this.collate=e.collate;}};var B=class extends w{constructor(e,r,o={}){super("");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=true;this.folder="column";this.file="column_type";this.isRawValue=false;this.column=e,this.dataType=r,this.length=o.length,this.precision=o.precision,this.scale=o.scale,this.enumValues=o.enumValues,this.withTimezone=o.withTimezone,this.autoIncrement=o.autoIncrement,this.autoCreate=o.autoCreate,this.autoUpdate=o.autoUpdate,this.collate=o.collate,this.isRawValue=o.isRawValue??false,this.unsigned=o.unsigned,this.zerofill=o.zerofill;}};var H=class extends w{constructor(e,r={},o=false){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="constraint";this.constraintType=e,this.columns=r.columns,this.references=r.references,this.constraintName=r.constraintName,this.onDelete=r.onDelete,this.onUpdate=r.onUpdate,this.defaultValue=r.defaultValue,this.checkExpression=r.checkExpression,this.isRawValue=o;}};var sr=class extends w{constructor(e,r=[],o=[],n=false,s){super("create table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="create_table";this.file="create_table";this.table=e,this.children=r,this.namedConstraints=o,this.ifNotExists=n,s&&Object.assign(this,s);}};var ir=class extends w{constructor(e,r=false){super("drop table");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="drop_table";this.file="drop_table";this.table=e,this.ifExists=r;}};var ar=class extends w{constructor(e,r=true){super("create extension");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="extension";this.file="create_extension";this.extensionName=e,this.ifNotExists=r;}};var lr=class extends w{constructor(e,r,o,n=false){super("create index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="index_op";this.file="create_index";this.table=e,this.columns=r,this.indexName=o,this.unique=n;}};var ur=class extends w{constructor(e,r,o){super("drop index");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.cascade=false;this.folder="index_op";this.file="drop_index";this.indexName=e,this.table=r,this.cascade=o??false;}};var St=class extends w{constructor(e,r=false,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 je=class extends w{constructor(e,r=false){super(r?"union all":"union");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="union";this.file="union";this.query=e,this.isAll=r;}};var at=class extends w{constructor(e,r,o){e==="normal"&&(e="");super("with");this.chainsWith=",";this.canKeywordBeSeenMultipleTimes=false;this.folder="with";this.file="with";this.alias=r,this.body=o,this.clause=e;}};var me=class extends w{constructor(e,r,o,n){super("select");this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="select";this.file="select";this.column=e,this.alias=r,this.sqlFunction=o,this.isRawValue=n??false;}};var lt=class extends w{constructor(e,r=false){super("truncate",r);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="truncate";this.file="truncate";this.fromNode=e;}};var Fe=class extends w{constructor(e,r,o=false,n,s,a=false){super("having",a);this.chainsWith="and";this.canKeywordBeSeenMultipleTimes=false;this.folder="having";this.file="having";this.column=e,this.chainsWith=`${r} `,this.isNegated=o,this.operator=n,this.value=s;}};var dr=class extends w{constructor(){super("distinct");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinct";this.file="distinct";}};var mr=class extends w{constructor(e){super("select");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="distinctOn";this.file="distinct_on";this.columns=e;}};var Ee=class extends w{constructor(e,r,o,n="extract",s=false){super("select");this.folder="select";this.file="select_json";this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.column=e,this.jsonPath=r,this.alias=o,this.jsonOperator=n,this.isRawValue=s;}};var ie=class extends w{constructor(e,r,o,n="inner",s,a=false,l){super(`${n} join`,a);this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="join";this.file="join";this.type="inner";this.table=e,this.left=r,this.right=o,this.on=s,this.additionalConditions=l;}};var Ct=class extends w{constructor(e,r=false){super("group by",r);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="group_by";this.file="group_by";this.column=e;}};var cr=class extends w{constructor(e){super("limit");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="limit";this.file="limit";this.limit=e;}};var pr=class extends w{constructor(e){super("offset");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="offset";this.file="offset";this.offset=e;}};var qt=class extends w{constructor(e,r="asc",o=false){super("order by",o);this.chainsWith=", ";this.canKeywordBeSeenMultipleTimes=false;this.folder="order_by";this.file="order_by";this.column=e,this.direction=r;}};var yr=class yr{constructor(t,e){this.model=t,this.sqlDataSource=e,this.groupByNodes=[],this.orderByNodes=[],this.limitNode=null,this.offsetNode=null,this.logs=this.sqlDataSource.logs,typeof t.getColumns=="function"?(this.modelColumns=t.getColumns(),this.modelColumnsMap=t.getColumnsByName?.()??new Map(this.modelColumns.map(r=>[r.columnName,r]))):(this.modelColumns=[],this.modelColumnsMap=yr.EMPTY_MAP);}clearGroupBy(){return this.groupByNodes=[],this}clearOrderBy(){return this.orderByNodes=[],this}clearLimit(){return this.limitNode=null,this}clearOffset(){return this.offsetNode=null,this}groupBy(...t){return t.forEach(e=>{this.groupByNodes.push(new Ct(e));}),this}groupByRaw(t){return this.groupByNodes.push(new Ct(t,true)),this}orderBy(t,e){return this.orderByNodes.push(new qt(t,e)),this}orderByRaw(t){return this.orderByNodes.push(new qt(t,"asc",true)),this}limit(t){return typeof t!="number"&&R.warn(`${this.model.name}::limit Non numeric value provided to \`limit\``),this.limitNode=new cr(t),this}offset(t){return typeof t!="number"&&R.warn(`${this.model.name}::offset Non numeric value provided to \`offset\``),this.offsetNode=new pr(t),this}};yr.EMPTY_MAP=new Map;var fr=yr;var Ue=class i{constructor(t,e=false){this.sqlDataSource=t;this.isNestedCondition=false;this.whereNodes=[],this.isNestedCondition=e;}getConditions(){return this.whereNodes}where(t,e,r){return typeof t=="function"?this.andWhereGroup(t):this.andWhere(t,e,r)}andWhere(t,e,r){if(typeof t=="function")return this.andWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",false,o,n)),this}orWhere(t,e,r){if(typeof t=="function")return this.orWhereGroup(t);let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",false,o,n)),this}whereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}andWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"and",true,o,n)),this}orWhereNot(t,e,r){let o="=",n;return typeof e=="string"&&r!==void 0?(o=e,n=r):(n=e,o="="),this.whereNodes.push(new x(t,"or",true,o,n)),this}whereBetween(t,e,r){return this.andWhereBetween(t,e,r)}andWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"and",false,"between",[e,r])),this}orWhereBetween(t,e,r){return this.whereNodes.push(new x(t,"or",false,"between",[e,r])),this}whereNotBetween(t,e,r){return this.andWhereNotBetween(t,e,r)}andWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"and",true,"between",[e,r])),this}orWhereNotBetween(t,e,r){return this.whereNodes.push(new x(t,"or",true,"between",[e,r])),this}whereLike(t,e){return this.andWhereLike(t,e)}andWhereLike(t,e){return this.where(t,"like",e),this}orWhereLike(t,e){return this.orWhere(t,"like",e),this}whereILike(t,e){return this.andWhereILike(t,e)}andWhereILike(t,e){return this.where(t,"ilike",e),this}orWhereILike(t,e){return this.orWhere(t,"ilike",e),this}whereNotLike(t,e){return this.andWhereNotLike(t,e)}andWhereNotLike(t,e){return this.where(t,"not like",e),this}orWhereNotLike(t,e){return this.orWhere(t,"not like",e),this}whereNotILike(t,e){return this.andWhereNotILike(t,e)}andWhereNotILike(t,e){return this.where(t,"not ilike",e),this}orWhereNotILike(t,e){return this.orWhere(t,"not ilike",e),this}whereIn(t,e){return this.andWhereIn(t,e)}andWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",false,"in",e)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this)}orWhereIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",false,"in",e)),this):(this.whereNodes.push(new x("false","or",true,"=",[],true)),this)}whereNotIn(t,e){return this.andWhereNotIn(t,e)}andWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"and",true,"in",e)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this)}orWhereNotIn(t,e){return e.length?(this.whereNodes.push(new x(t,"or",true,"in",e)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this)}whereNull(t){return this.andWhereNull(t)}andWhereNull(t){return this.whereNodes.push(new x(t,"and",false,"is null",void 0)),this}orWhereNull(t){return this.whereNodes.push(new x(t,"or",false,"is null",void 0)),this}whereNotNull(t){return this.andWhereNotNull(t)}andWhereNotNull(t){return this.whereNodes.push(new x(t,"and",false,"is not null",void 0)),this}orWhereNotNull(t){return this.whereNodes.push(new x(t,"or",false,"is not null",void 0)),this}whereRegexp(t,e){return this.andWhereRegexp(t,e)}andWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",false,r?"~":"regexp",e.source)),this}orWhereRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",false,r?"~":"regexp",e.source)),this}whereNotRegexp(t,e){return this.andWhereNotRegexp(t,e)}andWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"and",true,r?"~":"regexp",e.source)),this}orWhereNotRegexp(t,e){let r=this.sqlDataSource.getDbType()==="postgres"||this.sqlDataSource.getDbType()==="cockroachdb";return this.whereNodes.push(new x(t,"or",true,r?"~":"regexp",e.source)),this}whereGroup(t){return this.andWhereGroup(t)}andWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"and")),this}orWhereGroup(t){let e=new i(this.sqlDataSource,true);t(e);let r=e.getConditions();return r.length>0&&this.whereNodes.push(new Se(r,"or")),this}whereRaw(t,e){return this.andWhereRaw(t,e)}andWhereRaw(t,e){return this.whereNodes.push(new x(t,"and",true,"=",e??[],true)),this}orWhereRaw(t,e){return this.whereNodes.push(new x(t,"or",true,"=",e??[],true)),this}};var hr=class extends fr{constructor(t,e){super(t,e),this.joinNodes=[];}clearJoin(){return this.joinNodes=[],this}joinRaw(t){return this.joinNodes.push(new ie(t,"","","inner",{operator:"="},true)),this}leftJoinRaw(t){return this.joinNodes.push(new ie(t,"","","left",{operator:"="},true)),this}rightJoinRaw(t){return this.joinNodes.push(new ie(t,"","","right",{operator:"="},true)),this}fullJoinRaw(t){return this.joinNodes.push(new ie(t,"","","full",{operator:"="},true)),this}crossJoinRaw(t){return this.joinNodes.push(new ie(t,"","","cross",{operator:"="},true)),this}naturalJoinRaw(t){return this.joinNodes.push(new ie(t,"","","natural",{operator:"="},true)),this}innerJoin(t,e,r,o,n){let s=r,a=o,l=typeof o=="function"?o:n;if(!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}return this.join(typeof t=="string"?t:t.table,e,s,a,l),this}join(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"inner",{operator:a||"="},false,u)),this}leftJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"left",{operator:a||"="},false,u)),this}rightJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"right",{operator:a||"="},false,u)),this}fullJoin(t,e,r,o,n){let s=r,a="=",l;if(typeof o=="function"?l=o:typeof o=="string"&&(a=o,l=n),!s){if(!this.model.primaryKey)throw new g("JoinQueryBuilder::join","MODEL_HAS_NO_PRIMARY_KEY");s=`${this.model.table}.${this.model.primaryKey}`;}let u;if(l){let d=new Ue(this.sqlDataSource);l(d),u=d.getConditions();}return this.joinNodes.push(new ie(typeof t=="string"?t:t.table,e,s,"full",{operator:a||"="},false,u)),this}};var gr=class extends hr{constructor(e,r){super(e,r);this.modelSelectedColumns=[];this.dbType=r.getDbType(),this.fromNode=new U(this.model.table||""),this.distinctNode=null,this.distinctOnNode=null,this.selectNodes=[];}select(...e){return e.forEach(r=>{if(Array.isArray(r)){let[s,a]=r;this.modelSelectedColumns.push(a);let l=J(s,this.model.databaseCaseConvention);this.selectNodes.push(new me(l,a));return}let o=r;this.modelSelectedColumns.push(o);let n=J(o,this.model.databaseCaseConvention);this.selectNodes.push(new me(n));}),this}selectRaw(e){return this.selectNodes.push(new me(e,void 0,void 0,true)),this}selectFunc(e,r,o){let n=r==="*"?"*":J(r,this.model.databaseCaseConvention);return this.selectNodes.push(new me(`${e.toLowerCase()}(${n}) as ${o}`,void 0,void 0,true)),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}clearFrom(){return this.fromNode=new U(this.model.table||""),this}clearDistinct(){return this.distinctNode=null,this}clearDistinctOn(){return this.distinctOnNode=null,this}table(e){return this.fromNode=new U(e),this}distinct(){return this.distinctNode=new dr,this}distinctOn(...e){return this.distinctOnNode=new mr(e),this}selectJson(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract")),this}selectJsonText(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"extract_text")),this}selectJsonArrayLength(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"array_length")),this}selectJsonKeys(e,r,o){return this.selectNodes.push(new Ee(e,r,o,"object_keys")),this}selectJsonRaw(e,r){return this.selectNodes.push(new Ee(e,"",r,"raw",true)),this}};var br=class extends gr{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 Q&&o===void 0?this.andWhereSubQuery(e,"in",r):typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||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 Q&&o===void 0)return this.andWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.orWhereSubQuery(e,"in",r);if(typeof r=="string"&&r!=="="&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(e,"or",false,n,s)),this}whereColumn(e,r,o){return this.andWhereColumn(e,r,o)}andWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"and",false,n,new I(s))),this}orWhereColumn(e,r,o){let n="=",s;return o!==void 0?(n=r,s=o):s=r,this.whereNodes.push(new x(e,"or",false,n,new I(s))),this}whereNot(e,r,o){if(typeof r=="function"&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(r instanceof Q&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.andWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.andWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 Q&&o===void 0)return this.orWhereSubQuery(e,"not in",r);if(typeof r=="string"&&o!==void 0&&(o instanceof Q||typeof o=="function"))return this.orWhereSubQuery(e,r,o);let n="=",s;return typeof r=="string"&&o!==void 0&&!(o instanceof Q)&&typeof o!="function"?(n=r,s=o):(s=r,n="="),this.whereNodes.push(new x(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 x(e,"and",false,"between",[r,o])),this}orWhereBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",true,"between",[r,o])),this}orWhereNotBetween(e,r,o){return this.whereNodes.push(new x(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 x(e,"and",false,"in",r)),this):(this.whereNodes.push(new x("false","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"in",r)}orWhereIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",false,"in",r)),this):(this.whereNodes.push(new x("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 x(e,"and",true,"in",r)),this):(this.whereNodes.push(new x("true","and",true,"=",[],true)),this):this.andWhereSubQuery(e,"not in",r)}orWhereNotIn(e,r){return Array.isArray(r)?r.length?(this.whereNodes.push(new x(e,"or",true,"in",r)),this):(this.whereNodes.push(new x("true","or",true,"=",[],true)),this):this.orWhereSubQuery(e,"not in",r)}whereNull(e){return this.andWhereNull(e)}andWhereNull(e){return this.whereNodes.push(new x(e,"and",false,"is null",void 0)),this}orWhereNull(e){return this.whereNodes.push(new x(e,"or",false,"is null",void 0)),this}whereNotNull(e){return this.andWhereNotNull(e)}andWhereNotNull(e){return this.whereNodes.push(new x(e,"and",false,"is not null",void 0)),this}orWhereNotNull(e){return this.whereNodes.push(new x(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 x(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 x(e,"or",false,o?"~":"regexp",r.source)),this}whereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}andWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"and",true,o?"~":"regexp",r.source)),this}orWhereNotRegexp(e,r){let o=this.sqlDataSource.getDbType()==="postgres";return this.whereNodes.push(new x(e,"or",true,o?"~":"regexp",r.source)),this}whereExists(e){return this.andWhereExists(e)}andWhereExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","exists",r.extractQueryNodes(),"and")),this}orWhereExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","exists",r.extractQueryNodes(),"or")),this}whereNotExists(e){return this.andWhereNotExists(e)}andWhereNotExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","not exists",r.extractQueryNodes(),"and")),this}orWhereNotExists(e){let r=e instanceof Q?e:new Q(this.model,this.sqlDataSource);return r.isNestedCondition=true,typeof e=="function"&&e(r),this.whereNodes.push(new ye("","not exists",r.extractQueryNodes(),"or")),this}whereRaw(e,r=[]){return this.andWhereRaw(e,r)}andWhereRaw(e,r=[]){return this.whereNodes.push(new x(e,"and",false,"=",r,true)),this}orWhereRaw(e,r=[]){return this.whereNodes.push(new x(e,"or",false,"=",r,true)),this}having(e,r,o){return this.andHaving(e,r,o)}andHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"and",false,n,s)),this}orHaving(e,r,o){let n="=",s;return typeof r=="string"&&o?(n=r,s=o):(s=r,n="="),this.havingNodes.push(new Fe(e,"or",false,n,s)),this}havingRaw(e){return this.andHavingRaw(e)}andHavingRaw(e){return this.havingNodes.push(new Fe(e,"and",false,"=",[],true)),this}orHavingRaw(e){return this.havingNodes.push(new Fe(e,"or",false,"=",[],true)),this}buildSubQuery(e){if(e instanceof Q)return e;let r=new Q(this.model,this.sqlDataSource),o=e(r);return o!=null&&"extractQueryNodes"in o?o:r}andWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new ye(e,r,n.extractQueryNodes(),"and")),this}orWhereSubQuery(e,r,o){let n=this.buildSubQuery(o);return this.whereNodes.push(new ye(e,r,n.extractQueryNodes(),"or")),this}andWhereGroup(e){let r=new Q(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"and");return this.whereNodes.push(o),this}orWhereGroup(e){let r=new Q(this.model,this.sqlDataSource);r.isNestedCondition=true,e(r);let o=new Se(r.whereNodes,"or");return this.whereNodes.push(o),this}};var Tr=class extends br{whereJson(t,e){return this.andWhereJson(t,e)}andWhereJson(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJson(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereJsonNotContains(t,e){return this.andWhereJsonNotContains(t,e)}andWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereJsonNotContains(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonContains(t,e){return this.andWhereJsonContains(t,e)}andWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"and",false,"contains",e)),this}orWhereJsonContains(t,e){return this.whereNodes.push(new se(t,"or",false,"contains",e)),this}whereNotJson(t,e){return this.andWhereNotJson(t,e)}andWhereNotJson(t,e){return this.whereNodes.push(new se(t,"and",true,"not contains",e)),this}orWhereNotJson(t,e){return this.whereNodes.push(new se(t,"or",true,"not contains",e)),this}whereJsonRaw(t,e){return this.andWhereJsonRaw(t,e)}andWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"and",false,"raw",e)),this}orWhereJsonRaw(t,e){return this.whereNodes.push(new se(t,"or",false,"raw",e)),this}};var Q=class i extends Tr{constructor(e,r){super(e,r);this.isNestedCondition=false;this._interpreterUtils=null;this.insertNode=null;this.onDuplicateNode=null;this.updateNode=null;this.deleteNode=null;this.truncateNode=null;this.replicationMode=null;this.dbType=r.getDbType(),this.isNestedCondition=false,this.model=e,this.unionNodes=[],this.lockQueryNodes=[],this.withNodes=[],this.astParser=new N(this.model,this.dbType);}get interpreterUtils(){return this._interpreterUtils||(this._interpreterUtils=new h(this.model)),this._interpreterUtils}setReplicationMode(e){return this.replicationMode=e,this}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof i)&&typeof e[1]=="string"){let[r,o]=e;if(typeof r=="function"){let n=new i(this.model,this.sqlDataSource),s=r(n),a=s!=null&&"extractQueryNodes"in s?s:n;return this.selectNodes.push(new me(a.extractQueryNodes(),o)),this}return this.selectNodes.push(new me(r.extractQueryNodes(),o)),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}clearSelect(){return super.clearSelect(),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}async exists(){return !!await this.one()}async many(){let{sql:e,bindings:r}=this.unWrap();return this.execSqlWithSlaveHandling("read",o=>z(e,r,o,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"fetch"}}))}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async pluck(e){return (await this.many()).map(o=>o[e])}async one(){let e=await this.limit(1).many();return !e||!e.length?null:e[0]}async oneOrFail(){let e=await this.one();if(!e)throw new g("SqlDataSource::query::oneOrFail","ROW_NOT_FOUND");return e}async stream(e={}){let{sql:r,bindings:o}=this.unWrap();return this.execSqlWithSlaveHandling("read",async n=>await Yt(r,o,n,e,{onData:(a,l)=>{a.write(l);}}))}async*chunk(e){let r=0;for(;;){let o=await this.limit(e).offset(r).many();if(!o.length)break;r+=o.length,yield o;}}async paginateWithCursor(e,r,o){let n=this.clone();this.orderByNodes.length||this.orderBy(r.discriminator,r.orderBy||"asc"),o&&this.where(o.key,r.operator||">",o.value),this.limit(e);let[s,a]=await this.executePaginateQueries(()=>this.many(),()=>n.getCount()),l=s[s.length-1],u=l?l[r.discriminator]:null;return [{paginationMetadata:py(e,a),data:s},{key:r.discriminator,value:u}]}lockForUpdate(e={}){return this.lockQueryNodes.push(new St("for_update",e.skipLocked,e.noWait)),this}forShare(e={}){return this.lockQueryNodes.push(new St("for_share",e.skipLocked,e.noWait)),this}union(e){if(typeof e=="string")return this.unionNodes.push(new je(e)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o)),this}unionAll(e){if(typeof e=="string")return this.unionNodes.push(new je(e,true)),this;let o=(e instanceof i?e:e(new i(this.model,this.sqlDataSource))).extractQueryNodes();return this.unionNodes.push(new je(o,true)),this}increment(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} + ${r}`)})}decrement(e,r=1){return this.update({[e]:this.sqlDataSource.rawStatement(`${e} - ${r}`)})}async getCount(e="*"){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getMax(e){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getMin(e){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getAvg(e){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async getSum(e){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let r=await this.one();return r?nt(r.total):0}async paginate(e,r){(typeof e!="number"||typeof r!="number")&&R.warn(`${this.model.name}::paginate Non numeric values provided to \`paginate\``);let o=this.clone(),n=this.limit(r).offset((e-1)*r),[s,a]=await this.executePaginateQueries(()=>n.many(),()=>o.getCount("*"));return {paginationMetadata:Gt(e,r,a),data:s}}table(e,r){if(typeof e=="function"){if(!r)throw new g("QueryBuilder::table","MISSING_ALIAS_FOR_SUBQUERY");let o=new i(this.model,this.sqlDataSource),n=e(o),a=(n!=null&&"extractQueryNodes"in n?n:o).extractQueryNodes();return this.fromNode=new U(a,r),this}return this.fromNode=new U(e,r),this}with(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new at("normal",e,s.extractQueryNodes())),this}withRecursive(e,r){let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new at("recursive",e,s.extractQueryNodes())),this}withMaterialized(e,r){if(this.dbType!=="postgres"&&this.dbType!=="cockroachdb")throw new g("QueryBuilder::withMaterialized","MATERIALIZED_CTE_NOT_SUPPORTED",new Error("MATERIALIZED CTE is only supported by postgres"));let o=new i(this.model,this.sqlDataSource),n=r(o),s=n!=null&&"extractQueryNodes"in n?n:o;return this.withNodes.push(new at("materialized",e,s.extractQueryNodes())),this}insert(e,r){let o=Object.fromEntries(Object.keys(e).map(s=>[s,e[s]])),n=!r||r.length===0;return this.insertNode=new G(this.fromNode,[o],r,n),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:s,values:a}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),l=Object.fromEntries(s.map((p,f)=>[p,a[f]]));this.insertNode=new G(this.fromNode,[l],r,n);let{sql:u,bindings:d}=this.astParser.parse([this.insertNode]),m=await this.getSqlDataSource("write"),c=await z(u,d,m,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertOne",models:[e]}});if(!n)return Array.isArray(c)&&c.length?c[0]:c})}insertMany(e,r){let o=e.map(s=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a]]))),n=!r||r.length===0;return this.insertNode=new G(this.fromNode,o,r,n),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{if(!e.length)return n?void 0:[];let s=await Promise.all(e.map(async m=>{let{columns:c,values:p}=await this.interpreterUtils.prepareColumns(Object.keys(m),Object.values(m),"insert");return Object.fromEntries(c.map((f,y)=>[f,p[y]]))}));this.insertNode=new G(this.fromNode,s,r,n);let{sql:a,bindings:l}=this.astParser.parse([this.insertNode]),u=await this.getSqlDataSource("write"),d=await z(a,l,u,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"insertMany",models:s}});if(!n)return d})}upsert(e,r,o={updateOnConflict:true}){let n=Object.keys(e),s=Object.keys(r),a=Object.fromEntries(Object.keys(e).map(l=>[l,e[l]]));return this.insertNode=new G(new U(this.model.table),[a],void 0,true),this.onDuplicateNode=new he(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:l,values:u}=await this.interpreterUtils.prepareColumns(Object.keys(e),Object.values(e),"insert"),d=Object.fromEntries(l.map((y,T)=>[y,u[T]]));if(this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw([d],s,n,o,[e]);let{sql:m,bindings:c}=this.astParser.parse([new G(new U(this.model.table),[d],void 0,true),new he(this.model.table,s,n,o.updateOnConflict??true?"update":"ignore",o.returning)]),p=await this.getSqlDataSource("write"),f=await z(m,c,p,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:[e]}});return Array.isArray(f)?f:[f]})}upsertMany(e,r,o,n={updateOnConflict:true}){let s=o.map(a=>Object.fromEntries(Object.keys(a).map(l=>[l,a[l]])));return this.insertNode=new G(new U(this.model.table),s,void 0,true),this.onDuplicateNode=new he(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let a=[];if(await Promise.all(o.map(async c=>{let{columns:p,values:f}=await this.interpreterUtils.prepareColumns(Object.keys(c),Object.values(c),"insert"),y=Object.fromEntries(p.map((T,b)=>[T,f[b]]));a.push(y);})),this.sqlDataSource.type==="mssql")return this.executeMssqlMergeRaw(a,e,r,n,o);let{sql:l,bindings:u}=this.astParser.parse([new G(new U(this.model.table),a,void 0,true),new he(this.model.table,e,r,n.updateOnConflict??true?"update":"ignore",n.returning)]),d=await this.getSqlDataSource("write"),m=await z(l,u,d,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:o}});return Array.isArray(m)?m:[m]})}async executeMssqlMergeRaw(e,r,o,n,s){if(!e.length)return [];let a=Object.keys(e[0]),l=this.interpreterUtils.formatStringColumn("mssql",this.model.table),u=v=>this.interpreterUtils.formatStringColumn("mssql",v),d=[],m=e.map(v=>`select ${a.map($=>(d.push(v[$]),`@${d.length}`)).join(", ")}`),c=a.map(u).join(", "),p=m.join(" union all "),f=r.map(v=>`target.${u(v)} = source.${u(v)}`).join(" and "),y=o.filter(v=>!r.includes(v)).map(v=>`target.${u(v)} = source.${u(v)}`).join(", "),T=a.map(u).join(", "),b=a.map(v=>`source.${u(v)}`).join(", "),C=n.returning&&n.returning.length?n.returning.map(v=>`inserted.${u(v)}`).join(", "):a.map(v=>`inserted.${u(v)}`).join(", "),q=(n.updateOnConflict??true)&&y?`when matched then update set ${y}`:"",O=`merge into ${l} as target using (${p}) as source (${c}) on ${f} ${q} when not matched then insert (${T}) values (${b}) output ${C};`,D=await this.getSqlDataSource("write"),_=await z(O,d,D,this.dbType,"rows",{sqlLiteOptions:{typeofModel:this.model,mode:"raw",models:s}});return Array.isArray(_)?_:[_]}update(e,r){let o=Object.keys(e),n=Object.values(e);this.updateNode=new Me(this.fromNode,o,n,false,r);let s=r&&r.length>0;return new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:a,values:l}=await this.interpreterUtils.prepareColumns(o,n,"update");this.updateNode=new Me(this.fromNode,a,l,false,r);let{sql:u,bindings:d}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),m=await this.getSqlDataSource("write");return z(u,d,m,this.dbType,s?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:s?"fetch":"affectedRows"}})})}truncate(){return this.truncateNode=new lt(this.fromNode),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:e,bindings:r}=this.astParser.parse([this.truncateNode]),o=await this.getSqlDataSource("write");await z(e,r,o,this.dbType,"rows");})}delete(e){this.deleteNode=new rt(this.fromNode,false,e);let r=e&&e.length>0;return new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{sql:o,bindings:n}=this.astParser.parse([this.deleteNode,...this.whereNodes,...this.joinNodes]),s=await this.getSqlDataSource("write");return z(o,n,s,this.dbType,r?"rows":"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:r?"fetch":"affectedRows"}})})}softDelete(e={}){let{column:r="deletedAt",value:o=He()}=e||{};return this.updateNode=new Me(this.fromNode,[r],[o]),new Z(()=>this.unWrap(),()=>this.toSql(),()=>this.toQuery(),async()=>{let{columns:n,values:s}=await this.interpreterUtils.prepareColumns([r],[o],"update");this.updateNode=new Me(this.fromNode,n,s);let{sql:a,bindings:l}=this.astParser.parse([this.updateNode,...this.whereNodes,...this.joinNodes]),u=await this.getSqlDataSource("write");return z(a,l,u,this.dbType,"affectedRows",{sqlLiteOptions:{typeofModel:this.model,mode:"affectedRows"}})})}toQuery(){let{sql:e,bindings:r}=this.toSql();return Ge(e,r)}toSql(){let{sql:e,bindings:r}=this.unWrap(),o=Xe(this.sqlDataSource,e);return {sql:this.withQuery?`${this.withQuery} ${o}`:o,bindings:[...r||[]]}}unWrap(){this.selectNodes.length||(this.selectNodes=[new me("*")]);let{sql:e,bindings:r}=this.astParser.parse(this.extractQueryNodes());return {sql:this.withQuery?`${this.withQuery} ${e}`:e,bindings:[...r||[]]}}clone(){let e=new i(this.model,this.sqlDataSource);return e.dbType=this.dbType,e.modelSelectedColumns=j(this.modelSelectedColumns),e.distinctNode=j(this.distinctNode),e.distinctOnNode=j(this.distinctOnNode),e.selectNodes=j(this.selectNodes),e.withQuery=j(this.withQuery),e.joinNodes=j(this.joinNodes),e.whereNodes=j(this.whereNodes),e.groupByNodes=j(this.groupByNodes),e.havingNodes=j(this.havingNodes),e.orderByNodes=j(this.orderByNodes),e.lockQueryNodes=j(this.lockQueryNodes),e.unionNodes=j(this.unionNodes),e.withNodes=j(this.withNodes),e.fromNode=j(this.fromNode),e.limitNode=j(this.limitNode),e.offsetNode=j(this.offsetNode),e.isNestedCondition=this.isNestedCondition,e}clear(){let e=new i(this.model,this.sqlDataSource);return this.fromNode.alias&&e.table(e.model.table,this.fromNode.alias),e}clearLockQuery(){return this.lockQueryNodes=[],this}clearUnionQuery(){return this.unionNodes=[],this}clearWithQuery(){return this.withNodes=[],this}extractQueryNodes(){return this.selectNodes.length||(this.selectNodes=[new me("*")]),this.insertNode?[this.insertNode,this.onDuplicateNode].filter(Boolean):this.updateNode?[this.updateNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.deleteNode?[this.deleteNode,...this.whereNodes,...this.joinNodes,...this.orderByNodes,this.limitNode].filter(Boolean):this.truncateNode?[this.truncateNode]:[...this.withNodes,this.distinctNode,this.distinctOnNode,...this.selectNodes,this.fromNode,...this.joinNodes,...this.whereNodes,...this.groupByNodes,...this.havingNodes,...this.orderByNodes,this.limitNode,this.offsetNode,...this.lockQueryNodes,...this.unionNodes].filter(Boolean)}clearForFunctions(){return this.clearSelect(),this.clearGroupBy(),this.clearOrderBy(),this.clearLimit(),this.clearOffset(),this}isMssqlTransaction(){return this.sqlDataSource.type==="mssql"&&!!this.sqlDataSource.sqlConnection}async executePaginateQueries(e,r){if(this.isMssqlTransaction()){let o=await e(),n=await r();return [o,n]}return Promise.all([e(),r()])}async getSqlDataSource(e){return this.replicationMode?this.replicationMode==="master"?this.sqlDataSource:e==="write"?this.sqlDataSource:this.sqlDataSource.getSlave()||this.sqlDataSource:e==="read"?this.sqlDataSource.getSlave()||this.sqlDataSource:this.sqlDataSource}async execSqlWithSlaveHandling(e,r){let o=await this.getSqlDataSource(e);if(!(o!==this.sqlDataSource))return r(o);try{return await r(o)}catch(s){let a=s instanceof Error?s:new Error(String(s)),l=this.sqlDataSource.getOnSlaveServerFailure();if(l)return await l(a,{host:o.host,port:o.port,username:o.username,password:o.password,database:o.database,type:o.getDbType()}),await r(this.sqlDataSource);throw a}}};function fy(i,t){return t.strategy&&t.strategy!=="auto"?t.strategy:jh(i)}function jh(i){let{parentCount:t,relationType:e,hasLimitOffset:r}=i;return r&&(e==="hasMany"||e==="manyToMany")?"batched":t===1?"join":e==="manyToMany"?typeof t=="number"&&t<=10?"join":"batched":typeof t=="number"&&t<10?"join":"batched"}var Ie=class i extends Q{constructor(e,r){super(e,r);this.loadOptions={strategy:"auto"};this.sqlModelManagerUtils=new Nt(e,this.dbType,r),this.relationQueryBuilders=[],this.modelSelectedColumns=[],this.modelColumnsMap=this.model.getColumnsByDatabaseName(),this.modelColumnsDatabaseNames=new Map;for(let[o,n]of this.modelColumnsMap)this.modelColumnsDatabaseNames.set(o,n.columnName);}get isRelationQueryBuilder(){return !!this.relation}static from(e,r={}){if(r.connection)return new i(e,r.connection);if(r.trx)return new i(e,r.trx.sql);throw new Error("ModelQueryBuilder::from - A connection or transaction is required. Use sql.from(Model) instead.")}async one(e={}){let r=await this.limit(1).many(e);return !r||!r.length?null:r[0]}async oneOrFail(e){let r=await this.one(e);if(!r)throw new g(this.model.name+"::oneOrFail","ROW_NOT_FOUND");return r}async many(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let o=(await super.many()).map(a=>this.addAdditionalColumnsToModel(a));if(!o.length)return [];let n=await Ae(o,this.model,this.modelSelectedColumns);if(!n)return [];let s=Array.isArray(n)?n:[n];return e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.(s),this.relationQueryBuilders.length&&await this.processRelationsWithStrategy(s),s}then(e,r){return this.many().then(e,r)}catch(e){return this.many().catch(e)}finally(e){return this.many().finally(e)}async*chunk(e,r={}){let o=0;for(;;){let n=await this.limit(e).offset(o).many(r);if(!n.length)break;yield n,o+=n.length;}}async stream(e={}){!e.ignoreHooks?.includes("beforeFetch")&&await this.model.beforeFetch?.(this);let{sql:r,bindings:o}=this.unWrap(),n=await this.getSqlDataSource("read");return await Yt(r,o,n,e,{onData:async(a,l)=>{let u=this.addAdditionalColumnsToModel(l),d=await Ae([u],this.model,this.modelSelectedColumns);d&&(e.ignoreHooks?.includes("afterFetch")||await this.model.afterFetch?.([d]),this.relationQueryBuilders.length&&await this.processRelationsRecursively([d]),a.write(d));}})}async paginateWithCursor(e,r,o){if(!r){if(!this.model.primaryKey)throw new g(this.model.name+"::paginateWithCursor","PRIMARY_KEY_NOT_FOUND");r={discriminator:this.model.primaryKey};}return super.paginateWithCursor(e,r,o)}insert(e,r={}){return this.getModelManager(r.trx).insert(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}insertMany(e,r={}){return this.getModelManager(r.trx).insertMany(e,{ignoreHooks:r.ignoreHooks,returning:r.returning})}upsert(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=Object.keys(e),a=Object.keys(r),l={...e,...r};return n.upsertMany(s,a,[l],{updateOnConflict:o.updateOnConflict??true,returning:o.returning}).then(u=>Array.isArray(u)?u[0]:u)}upsertMany(e,r,o={updateOnConflict:true}){let n=this.getModelManager(o.trx),s=r.length>0?Object.keys(r[0]):[];return n.upsertMany(e,s,r,{updateOnConflict:o.updateOnConflict??true,returning:o.returning})}getModelManager(e){let r=e?e.sql:this.sqlDataSource.getTransactionBoundSqlDataSource()??this.sqlDataSource;return new Le(this.model,r)}async find(e){return this.getModelManager().find(e)}async findOne(e){return this.getModelManager().findOne(e)}async findOneOrFail(e){return this.getModelManager().findOneOrFail(e)}async findOneByPrimaryKey(e,r){return this.getModelManager().findOneByPrimaryKey(e,r)}async updateRecord(e,r,o){return this.getModelManager(o?.trx).updateRecord(e,r,o)}async deleteRecord(e,r){return this.getModelManager(r?.trx).deleteRecord(e)}async save(e,r){let o=this.model.primaryKey;if(!o)throw new g(this.model.name+"::save","MODEL_HAS_NO_PRIMARY_KEY");let n=e[o],s=n?{[o]:n}:{};return this.upsert(s,e,{updateOnConflict:true,returning:r?.returning,trx:r?.trx})}async softDeleteRecord(e,r,o){let{column:n=this.model.softDeleteColumn,value:s=this.model.softDeleteValue}=r||{},a={[n]:s};return this.getModelManager(o?.trx).updateRecord(e,a,{returning:o?.returning})}async firstOrInsert(e,r,o){let n=this.getModelManager(o?.trx),s=await n.findOne({where:e,ignoreHooks:["afterFetch","beforeFetch"]});if(s)return s;let a={...e,...r};return n.insert(a,{returning:["*"]})}async refresh(e){return this.getModelManager().findOneByPrimaryKey(e)}async sync(e,r,o,n,s={}){if(Array.isArray(o)||(o=[o]),!o.length)return;let a=this.sqlModelManagerUtils.getRelationFromModel(e);if(a.type!=="manyToMany")throw new g(`${this.model.name}::sync`,"RELATION_NOT_MANY_TO_MANY");let l=J(a.leftForeignKey,s.caseConvention||this.model.databaseCaseConvention),u=J(a.rightForeignKey,s.caseConvention||this.model.databaseCaseConvention),d=o.map((p,f)=>({[l]:r[this.model.primaryKey],[u]:p[a.model.primaryKey],...n?n(p,f):{}}));class m extends ne{static get table(){return a.throughModel}}m.databaseCaseConvention="preserve",m.modelCaseConvention="preserve",await new Le(m,s.trx?s.trx.sql:this.sqlDataSource).insertMany(d);}truncate(){return super.truncate()}update(e,r={}){let o=r.returning,n=super.update(e,o);return new Z(()=>n.unWrap(),()=>n.toSql(),()=>n.toQuery(),async()=>(r.ignoreBeforeUpdateHook||await this.model.beforeUpdate?.(this),n))}softDelete(e={}){let r=super.softDelete(e),{ignoreBeforeUpdateHook:o=false}=e||{};return new Z(()=>r.unWrap(),()=>r.toSql(),()=>r.toQuery(),async()=>(o||await this.model.beforeUpdate?.(this),r))}delete(e={}){let r=e.returning,o=super.delete(r);return new Z(()=>o.unWrap(),()=>o.toSql(),()=>o.toQuery(),async()=>(e.ignoreBeforeDeleteHook||await this.model.beforeDelete?.(this),o))}async getCount(e="*",r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`count(${e}) as total`);let o=r.ignoreHooks?["beforeFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMax(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`max(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getMin(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`min(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getAvg(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`avg(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async getSum(e,r={ignoreHooks:false}){this.clearForFunctions(),this.selectRaw(`sum(${e}) as total`);let o=r.ignoreHooks?["beforeFetch","afterFetch"]:[],n=await this.one({ignoreHooks:o});return n?+n.total:0}async paginate(e,r,o={ignoreHooks:false}){let n=this.clone(),s=this.limit(r).offset((e-1)*r),a=o.ignoreHooks?["beforeFetch","afterFetch"]:[],[l,u]=await this.executePaginateQueries(()=>s.many({ignoreHooks:a}),()=>n.getCount("*",{ignoreHooks:o.ignoreHooks}));return {paginationMetadata:Gt(e,r,u),data:l}}select(...e){if(e.length===2&&(typeof e[0]=="function"||e[0]instanceof Q)&&typeof e[1]=="string"){let[r,o]=e;return super.select(r,o),this}return super.select(...e),this}selectRaw(e){return super.selectRaw(e),this}selectFunc(e,r,o){return super.selectFunc(e,r,o),this}clearSelect(){return this.modelSelectedColumns=[],this.selectNodes=[],this}selectJson(e,r,o){return super.selectJson(e,r,o),this}selectJsonText(e,r,o){return super.selectJsonText(e,r,o),this}selectJsonArrayLength(e,r,o){return super.selectJsonArrayLength(e,r,o),this}selectJsonKeys(e,r,o){return super.selectJsonKeys(e,r,o),this}selectJsonRaw(e,r){return super.selectJsonRaw(e,r),this}load(e,r,o){let n,s={strategy:"auto"};typeof r=="function"?(n=r,o&&(s=o)):r&&typeof r=="object"&&(s=r);let a=this.sqlModelManagerUtils.getRelationFromModel(e),l=new i(a.model,this.sqlDataSource);return l.relation=a,l.loadOptions=s,n?.(l),this.relationQueryBuilders.push(l),this}clearRelations(){return this.relationQueryBuilders=[],this}havingRelated(e,r,o){return this.andHavingRelated(e,r,o)}andHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereExists(d),this}orHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereExists(d),this}notHavingRelated(e,r,o){return this.andNotHavingRelated(e,r,o)}andNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.whereNotExists(d),this}orNotHavingRelated(e,r,o){let n,s,a;typeof r=="function"?a=r:typeof r=="string"&&o!==void 0?(s=r,n=o):r!==void 0&&(n=r,s="=");let l=this.sqlModelManagerUtils.getRelationFromModel(e),u=new i(l.model,this.sqlDataSource);u.relation=l;let d=this.getRelatedModelsQueryForRelation(u,l,[]);return d.clearWhere(),d.clearSelect(),d.selectRaw("1"),a?.(d),this.applyHavingRelatedFilter(d,l,s,n),this.orWhereNotExists(d),this}clone(){let e=super.clone();return e.relationQueryBuilders=j(this.relationQueryBuilders),e}async processRelationsRecursively(e){await Promise.all(this.relationQueryBuilders.filter(r=>r.isRelationQueryBuilder).map(async r=>{let o=await this.getRelatedModelsForRelation(r,r.relation,e);this.mapRelatedModelsToModels(r.relation,e,o);}));}async processRelationsWithStrategy(e){let r=e.length,o=this.relationQueryBuilders.filter(s=>s.isRelationQueryBuilder),n=async s=>{let a=fy({parentCount:r,relationType:s.relation.type,hasLimitOffset:!!s.limitNode||!!s.offsetNode,hasOrderBy:s.orderByNodes.length>0},s.loadOptions),l=s.relationQueryBuilders.length>0;a==="join"&&!l?await this.loadRelationViaJoin(s,e):await this.loadRelationViaBatch(s,e);};if(this.dbType==="mssql"){for(let s of o)await n(s);return}await Promise.all(o.map(n));}async loadRelationViaJoin(e,r){let o=e.relation,n=e.loadOptions.joinSeparator||"__",a=await this.buildJoinQuery(e,o,n).many({ignoreHooks:["beforeFetch","afterFetch"]});this.mapJoinedResultsToModels(a,r,o,n);}buildJoinQuery(e,r,o){let n=new i(this.model,this.sqlDataSource);if(this.modelSelectedColumns.length>0)for(let s of this.selectNodes)n.selectNodes.push(j(s));else for(let[s]of this.model.getColumnsByDatabaseName())n.selectRaw(`${this.model.table}.${s}`);for(let s of this.whereNodes){let a=j(s);this.qualifyWhereNodeColumns(a,this.model.table),n.whereNodes.push(a);}for(let s of this.groupByNodes)n.groupByNodes.push(j(s));for(let s of this.orderByNodes)n.orderByNodes.push(j(s));switch((r.type==="hasOne"||r.type==="belongsTo")&&(this.limitNode&&(n.limitNode=j(this.limitNode)),this.offsetNode&&(n.offsetNode=j(this.offsetNode))),r.type){case "hasOne":case "hasMany":n.leftJoin(r.model.table,`${this.model.table}.${this.model.primaryKey}`,`${r.model.table}.${r.foreignKey}`);break;case "belongsTo":n.leftJoin(r.model.table,`${this.model.table}.${r.foreignKey}`,`${r.model.table}.${r.model.primaryKey}`);break;case "manyToMany":{let s=r;n.leftJoin(s.throughModel,`${this.model.table}.${this.model.primaryKey}`,`${s.throughModel}.${s.leftForeignKey}`),n.leftJoin(s.model.table,`${s.throughModel}.${s.rightForeignKey}`,`${s.model.table}.${s.model.primaryKey}`);break}}this.selectRelationColumnsWithAlias(n,r,e,o);for(let s of e.whereNodes)n.whereNodes.push(j(s));for(let s of e.orderByNodes)n.orderByNodes.push(j(s));return n}selectRelationColumnsWithAlias(e,r,o,n){let s=r.columnName,a=r.model,l=a.getColumnsByName(),u=a.getColumnsByDatabaseName(),d=o.selectNodes.filter(c=>typeof c.column=="string"),m=d.some(c=>c.column==="*"||c.column.endsWith(".*"));if(d.length===0||m)for(let[c,p]of u)e.selectRaw(`${a.table}.${c} as ${s}${n}${p.columnName}`);else for(let c of d){let p=c.column,f=p.includes(".")?p.split(".").pop():p,y=u.get(f)||l.get(f),T=y?.databaseName??f,b=c.alias??y?.columnName??f;e.selectRaw(`${a.table}.${T} as ${s}${n}${b}`);}}mapJoinedResultsToModels(e,r,o,n){let{columnName:s,type:a}=o,l=o.model.getColumnsByName();if(a==="hasMany"||a==="manyToMany"){let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];u.has(m)||u.set(m,[]);let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.get(m).push(c));}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||[];});}else {let u=new Map;e.forEach(d=>{let m=d[this.model.primaryKey];if(!u.has(m)){let c=this.extractRelationDataFromRow(d,s,n);c&&(this.serializeRelationData(c,l),u.set(m,c));}}),r.forEach(d=>{let m=d[this.model.primaryKey];d[s]=u.get(m)||null;});}}extractRelationDataFromRow(e,r,o){let n=`${r}${o}`,s={},a=false,l=false;for(let u of Object.keys(e))if(u.startsWith(n)){let d=u.substring(n.length);s[d]=e[u],a=true,e[u]!==null&&e[u]!==void 0&&(l=true);}return a&&l?s:null}qualifyWhereNodeColumns(e,r){if(e instanceof x)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof ye)e.column.includes(".")||(e.column=`${r}.${e.column}`);else if(e instanceof Se)for(let o of e.nodes)this.qualifyWhereNodeColumns(o,r);}serializeRelationData(e,r){for(let o of Object.keys(e)){let n=r.get(o);n?.serialize&&e[o]!==null&&e[o]!==void 0&&(e[o]=n.serialize(e[o]));}}async loadRelationViaBatch(e,r){let o=await this.getRelatedModelsForRelation(e,e.relation,r);this.mapRelatedModelsToModels(e.relation,r,o);}mapRelatedModelsToModels(e,r,o){switch(e.type){case "hasOne":if(!this.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::hasOne","MODEL_HAS_NO_PRIMARY_KEY");let n=new Map;o.forEach(c=>{let p=c[e.foreignKey];p&&n.set(String(p),c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=null;return}let f=n.get(String(p));c[e.columnName]=f||null;});break;case "belongsTo":let s=new Map;o.forEach(c=>{if(!e.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::belongsTo",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${e.model.name}`);let p=c[e.model.primaryKey];p&&s.set(String(p),c);}),r.forEach(c=>{let p=c[e.foreignKey];if(!p){c[e.columnName]=null;return}let f=s.get(String(p));c[e.columnName]=f||null;});break;case "hasMany":if(!this.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::hasMany","MODEL_HAS_NO_PRIMARY_KEY");let a=new Map;o.forEach(c=>{let p=c[e.foreignKey];if(!p)return;let f=String(p);a.has(f)||a.set(f,[]),a.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=a.get(String(p))||[];c[e.columnName]=f;});break;case "manyToMany":if(!this.model.primaryKey||!e.model.primaryKey)throw new g(this.model.name+"::mapRelatedModelsToModels::manyToMany","MODEL_HAS_NO_PRIMARY_KEY");let l=e,u=new Map,d=l.leftForeignKey,m=this.modelColumnsMap.get(d)||this.modelColumnsDatabaseNames.get(d)||J(d,this.model.modelCaseConvention);o.forEach(c=>{let p=c[m];if(p==null)return;let f=String(p);u.has(f)||u.set(f,[]),delete c[m],u.get(f).push(c);}),r.forEach(c=>{let p=c[this.model.primaryKey];if(!p){c[e.columnName]=[];return}let f=u.get(String(p))||[];c[e.columnName]=f;});break;default:throw new g(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=Re__default.default.randomBytes(6).toString("hex"),u=`${r.model.table}_cte_${l}`,d=e.orderByNodes.map(_=>_.isRawValue?_.column:`${this.interpreterUtils.formatStringColumn(this.dbType,_.column)} ${_.direction}`).join(", ")||["1"];e.clearLimit(),e.clearOffset();let m=e.with(u,_=>_.select(...e.modelSelectedColumns).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${this.interpreterUtils.formatStringColumn(this.dbType,r.foreignKey)} ORDER BY ${d}) as rn_${l}`).whereIn(r.foreignKey,n));s&&m.whereRaw(`rn_${l} <= ${s+(a||0)}`),a&&m.whereRaw(`rn_${l} > ${a}`);let c=e.modelSelectedColumns.map(_=>io(_,u,e.model.table));return m.select(...c).table(u);case "manyToMany":if(!this.model.primaryKey||!r.model.primaryKey)throw new g(this.model.name+"::getRelatedModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");let p=r;if(!o.length)return e;let f=e.limitNode?.limit,y=e.offsetNode?.offset,T=e.modelSelectedColumns.length?e.modelSelectedColumns.map(_=>_.includes(".")?_:`${r.model.table}.${_}`):[`${r.model.table}.*`];if(!f&&!y)return e.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,p.leftForeignKey]).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n);let b=Re__default.default.randomBytes(6).toString("hex"),C=`${r.model.table}_cte_${b}`,A=e.orderByNodes.map(_=>{if(_.isRawValue)return _.column;let v=_.column.includes(".")?_.column:`${r.model.table}.${_.column}`;return `${this.interpreterUtils.formatStringColumn(this.dbType,v)} ${_.direction}`}).join(", ")||["1"];e.clearLimit(),e.clearOffset(),e.clearOrderBy();let q=`${Re__default.default.randomBytes(6).toString("hex")}_left_foreign_key`,O=e.with(C,_=>_.select(...T).select([`${p.throughModel}.${p.leftForeignKey}`,q]).selectRaw(`ROW_NUMBER() OVER (PARTITION BY ${p.throughModel}.${this.interpreterUtils.formatStringColumn(this.dbType,p.leftForeignKey)} ORDER BY ${A}) as rn_${b}`).leftJoin(p.throughModel,`${p.relatedModel}.${p.model.primaryKey}`,`${p.throughModel}.${p.rightForeignKey}`).whereIn(`${p.throughModel}.${p.leftForeignKey}`,n));f&&O.whereRaw(`rn_${b} <= ${f+(y||0)}`),y&&O.whereRaw(`rn_${b} > ${y}`);let D=T.map(_=>io(_,C,e.model.table));return O.select(...D).select([`${C}.${q}`,p.leftForeignKey]).table(C);default:throw new g(this.model.name+"::getRelatedModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}getFilterValuesFromModelsForRelation(e,r){switch(e.type){case "hasMany":case "hasOne":if(!this.model.primaryKey)throw new g(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 g(this.model.name+"::getFilterValuesFromModelsForRelation","MODEL_HAS_NO_PRIMARY_KEY");return r.map(o=>o[this.model.primaryKey]);default:throw new g(this.model.name+"::getFilterValuesFromModelsForRelation","UNSUPPORTED_RELATION_TYPE")}}applyHavingRelatedFilter(e,r,o,n){let s=new h(r.model),a=new h(this.model),l=this.dbType;switch(r.type){case "hasOne":case "hasMany":{if(!this.model.primaryKey||!r.foreignKey)throw new g(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");let u=s.formatStringColumn(l,`${r.model.table}.${r.foreignKey}`),d=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "belongsTo":{if(!r.model.primaryKey||!r.foreignKey)throw new g(this.model.name+"::applyHavingRelatedFilter",`RELATED_MODEL_DOES_NOT_HAVE_A_PRIMARY_KEY_${r.model.name}`);let u=s.formatStringColumn(l,`${r.model.table}.${r.model.primaryKey}`),d=a.formatStringColumn(l,`${this.model.table}.${r.foreignKey}`);e.whereRaw(`${u} = ${d}`),o&&typeof n=="number"&&e.groupByRaw(u).andHavingRaw(`count(*) ${o} ${n}`);return}case "manyToMany":{let u=r;if(!this.model.primaryKey||!r.model.primaryKey)throw new g(this.model.name+"::applyHavingRelatedFilter","MODEL_HAS_NO_PRIMARY_KEY");e.joinNodes?.some(p=>!p.isRawValue&&p.table===u.throughModel&&p.type==="left")||e.leftJoin(u.throughModel,`${u.relatedModel}.${r.model.primaryKey}`,`${u.throughModel}.${u.rightForeignKey}`);let m=a.formatStringColumn(l,`${u.throughModel}.${u.leftForeignKey}`),c=a.formatStringColumn(l,`${this.model.table}.${this.model.primaryKey}`);e.whereRaw(`${m} = ${c}`),o&&typeof n=="number"&&e.groupByRaw(m).andHavingRaw(`count(*) ${o} ${n}`);return}default:throw new g(this.model.name+"::applyHavingRelatedFilter","UNSUPPORTED_RELATION_TYPE")}}addAdditionalColumnsToModel(e){let r={};return Object.entries(e).forEach(([o,n])=>{if(this.modelColumnsDatabaseNames.get(o)){r[o]=n;return}r[o]=n;}),r}};var kl=class{constructor(t,e,r){this.sqlDataSource=t,this.typeofModel=e,this.modelData=r;}merge(t){this.modelData={...this.modelData,...t};}getQueryBuilder(){return new Ie(this.typeofModel,this.sqlDataSource)}async create(t){if(t<=0)return [];let e=this.getQueryBuilder();if(t===1)return await e.insert(this.modelData,{returning:["*"]});let r=Array.from({length:t});return await e.insertMany(r.map(()=>({...this.modelData})),{returning:["*"]})}},Fh=(i,t,e)=>new kl(i,t,e);var ut=new Map,Pe=new Map,Nr=class{async get(t){return ut.get(t)}async set(t,e,r){let o=Pe.get(t);if(o&&(clearTimeout(o),Pe.delete(t)),ut.set(t,e),r){let n=setTimeout(()=>{ut.delete(t),Pe.delete(t);},r);Pe.set(t,n);}}async invalidate(t){let e=Pe.get(t);e&&(clearTimeout(e),Pe.delete(t)),ut.delete(t);}async invalidateAll(t){let e=ut.keys();for(let r of e)if(r.startsWith(t)){let o=Pe.get(r);o&&(clearTimeout(o),Pe.delete(r)),ut.delete(r);}}};var yy=class{constructor(t){this.ioRedisOptions=t;}async getClient(){if(this.redisInstance)return this.redisInstance;let{default:t}=await import('ioredis').catch(()=>{throw R.error("RedisCacheAdapter::getClient ioredis driver not found and required for the RedisCacheAdapter"),new k("ioredis")});return this.redisInstance=new t(this.ioRedisOptions),this.redisInstance}async get(t){let r=await(await this.getClient()).get(t);if(r!=null)return this.deserializeData(r)}async set(t,e,r){let o=await this.getClient(),n=this.serializeData(e);if(n){if(r){await o.set(t,n,"PX",r);return}await o.set(t,n);}}async invalidate(t){await(await this.getClient()).del(t);}async invalidateAll(t){let e=await this.getClient(),r=await e.keys(`${t}:*`);for(let o of r)await e.del(o);}serializeData(t){if(t!=null){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("base64");if(typeof t=="object"||Array.isArray(t))try{return JSON.stringify(t)}catch(e){throw R.error("RedisCacheAdapter::set failed to serialize data"),e}return String(t)}}deserializeData(t){try{return JSON.parse(t)}catch{return t}}async disconnect(){this.redisInstance&&await this.redisInstance.quit();}};var P={DB_TYPE:process.env.DB_TYPE,DB_HOST:process.env.DB_HOST,DB_PORT:process.env.DB_PORT,DB_USER:process.env.DB_USER,DB_PASSWORD:process.env.DB_PASSWORD,DB_DATABASE:process.env.DB_DATABASE,DB_LOGS:process.env.DB_LOGS==="true",MIGRATION_PATH:process.env.MIGRATION_PATH||"database/migrations",REDIS_HOST:process.env.REDIS_HOST,REDIS_PORT:process.env.REDIS_PORT,REDIS_USERNAME:process.env.REDIS_USERNAME,REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_DATABASE:process.env.REDIS_DATABASE,MONGO_URL:process.env.MONGO_URL,MONGO_LOGS:process.env.MONGO_LOGS==="true",MSSQL_TRUST_SERVER_CERTIFICATE:process.env.MSSQL_TRUST_SERVER_CERTIFICATE==="true"||false},Uh=()=>{if(!eo__default.default.existsSync(".env"))return P;try{eo__default.default.readFileSync(".env","utf8").split(`
191
191
  `).forEach(e=>{let[r,o]=e.split("="),n=r.trim(),s=o.trim();switch(n){case "DB_TYPE":P.DB_TYPE||(P.DB_TYPE=s);break;case "DB_HOST":P.DB_HOST||(P.DB_HOST=s);break;case "DB_PORT":P.DB_PORT||(P.DB_PORT=s);break;case "DB_USER":P.DB_USER||(P.DB_USER=s);break;case "DB_PASSWORD":P.DB_PASSWORD||(P.DB_PASSWORD=s);break;case "DB_DATABASE":P.DB_DATABASE||(P.DB_DATABASE=s);break;case "MIGRATION_PATH":P.MIGRATION_PATH||(P.MIGRATION_PATH=s||"database/migrations");break;case "REDIS_HOST":P.REDIS_HOST||(P.REDIS_HOST=s);break;case "REDIS_PORT":P.REDIS_PORT||(P.REDIS_PORT=s);break;case "REDIS_USERNAME":P.REDIS_USERNAME||(P.REDIS_USERNAME=s);break;case "REDIS_PASSWORD":P.REDIS_PASSWORD||(P.REDIS_PASSWORD=s);break;case "REDIS_DATABASE":P.REDIS_DATABASE||(P.REDIS_DATABASE=s);break;case "MONGO_URL":P.MONGO_URL||(P.MONGO_URL=s);break;case "MSSQL_TRUST_SERVER_CERTIFICATE":P.MSSQL_TRUST_SERVER_CERTIFICATE||(P.MSSQL_TRUST_SERVER_CERTIFICATE=s==="true");break}});}catch{}finally{return P}},E=Uh();var dt=class{constructor(t){switch(this.type=t?.type||E.DB_TYPE,this.type){case "mongo":this.handleMongoSource(t);break;case "cockroachdb":this.handleCockroachdbSource(t);break;case "postgres":this.handlePostgresSource(t);break;case "mariadb":case "mysql":this.handleMysqlSource(t);break;case "sqlite":this.handleSqliteSource(t);break;case "mssql":this.handleMssqlSource(t);break;case "oracledb":this.handleOracleDBSource(t);break;default:throw new g(`Invalid database type: ${this.type}, please provide a valid database type in your input or in the .env file with the key DB_TYPE
192
192
  Valid database types are: [mongo, postgres, cockroachdb, mysql, mariadb, sqlite]`,`UNSUPPORTED_DATABASE_TYPE_${this.type}`)}let e=Jt(this.logs);e?.customLogger&&R.setCustomLogger(e.customLogger);}handleCockroachdbSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=26257);}handlePostgresSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=5432);}handleMysqlSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=3306);}handleSqliteSource(t){this.database=t?.database||E.DB_DATABASE||":memory:",this.logs=t?.logs||E.DB_LOGS||false;}handleMongoSource(t){this.url=t?.url||E.MONGO_URL,this.logs=t?.logs||E.MONGO_LOGS||false;}handleMssqlSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=1433);}handleOracleDBSource(t){this.host=t?.host||E.DB_HOST,this.port=+t?.port||+E.DB_PORT,this.username=t?.username||E.DB_USER,this.password=t?.password||E.DB_PASSWORD,this.database=t?.database||E.DB_DATABASE,this.logs=t?.logs||E.DB_LOGS||false,this.port||(this.port=1521);}};var re=class{constructor(t){this.options=t;}static async createDriver(t){throw new g("Driver::createDriver This error should never happen. Please report it to the developers.","DEVELOPMENT_ERROR")}};var _t=class _t extends re{constructor(e,r){super(r);this.type="mongo";this.client=e;}static async createDriver(){if(this.mongoClient)return new _t(this.mongoClient);let e=await import('mongodb').catch(()=>{throw new k("mongodb")});if(this.mongoClient=e.default??e,!this.mongoClient)throw new k("mongodb");return new _t(this.mongoClient)}};_t.mongoClient=null;var wr=_t;var Rt=class Rt extends re{constructor(e,r){super(r);this.type="mssql";this.client=e;}static async createDriver(){if(this.mssqlClient)return new Rt(this.mssqlClient);let e=await import('mssql').catch(()=>{throw new k("mssql")});if(this.mssqlClient=e.default??e,!this.mssqlClient)throw new k("mssql");return new Rt(this.mssqlClient)}};Rt.mssqlClient=null;var Sr=Rt;var Mt=class Mt extends re{constructor(e,r){super(r);this.type="mysql";this.client=e;}static async createDriver(){if(this.mysqlClient)return new Mt(this.mysqlClient);let e=await import('mysql2/promise').catch(()=>{throw new k("mysql2")});if(this.mysqlClient=e.default??e,!this.mysqlClient)throw new k("mysql2");return new Mt(this.mysqlClient)}};Mt.mysqlClient=null;var Cr=Mt;var At=class At extends re{constructor(e,r){super(r);this.type="oracledb";this.client=e;}static async createDriver(){if(this.oracledbClient)return new At(this.oracledbClient);let e=await import('oracledb').catch(()=>{throw new k("oracledb")});if(this.oracledbClient=e.default??e,!this.oracledbClient)throw new k("oracledb");return new At(this.oracledbClient)}};At.oracledbClient=null;var qr=At;var Ot=class Ot extends re{constructor(e,r){super(r);this.type="postgres";this.client=e;}static async createDriver(){if(this.pgClient)return new Ot(this.pgClient);let e=await import('pg').catch(()=>{throw new k("pg")});if("default"in e&&(e.default,this.pgClient=e.default??e),!this.pgClient)throw new k("pg");return new Ot(this.pgClient)}};Ot.pgClient=null;var _r=Ot;var xt=class xt extends re{constructor(e,r){super(r);this.type="sqlite";this.client=e;}static async createDriver(){if(this.sqlite3Client)return new xt(this.sqlite3Client);let e=await import('sqlite3').catch(()=>{throw new k("sqlite3")});if(this.sqlite3Client=e.default??e,!this.sqlite3Client)throw new k("sqlite3");return new xt(this.sqlite3Client)}};xt.sqlite3Client=null;var Rr=xt;var ce=class{static async getDriver(t){let e=this.getExistingDriver(t);if(e)return e;switch(t){case "mysql":case "mariadb":return this.mysqlDriver=await Cr.createDriver(),this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver=await _r.createDriver(),this.pgDriver;case "sqlite":return this.sqliteDriver=await Rr.createDriver(),this.sqliteDriver;case "mongo":return this.mongodbDriver=await wr.createDriver(),this.mongodbDriver;case "mssql":return this.mssqlDriver=await Sr.createDriver(),this.mssqlDriver;case "oracledb":return this.oracledbDriver=await qr.createDriver(),this.oracledbDriver;default:throw new g(`DriverFactory::getDriver Driver ${t} not supported`,"DRIVER_NOT_FOUND")}}static getExistingDriver(t){switch(t){case "mysql":case "mariadb":return this.mysqlDriver;case "postgres":case "cockroachdb":return this.pgDriver;case "sqlite":return this.sqliteDriver;case "mongo":return this.mongodbDriver;case "mssql":return this.mssqlDriver;case "oracledb":return this.oracledbDriver;default:return null}}};ce.mysqlDriver=null,ce.pgDriver=null,ce.sqliteDriver=null,ce.mssqlDriver=null,ce.oracledbDriver=null,ce.mongodbDriver=null;var Ll=Symbol("mongoProperties");function Mr(){return (i,t)=>{let e=K.getMetadata(Ll,i)||[];e.push(t),K.defineMetadata(Ll,e,i);}}function gy(i){return K.getMetadata(Ll,i.prototype)||[]}function by(){return {$annotations:{}}}var mt=class extends De{static get collection(){if(!this._collection)throw new Error(`Collection name not set for ${this.name}. Use defineCollection() to create collections.`);return this._collection}static beforeFetch(t){}static beforeInsert(t){return t}static beforeUpdate(t){}static beforeDelete(t){}static async afterFetch(t){return t}};nu([Mr()],mt.prototype,"id");function Vh(i){return typeof i!="function"||!i.prototype}function Jh(i){let t={id:i._id?.toString()};for(let e of Object.keys(i))e!=="_id"&&(t[e]=i[e]);return t}async function ve(i,t,e){if(!t)return null;if(Vh(i))return Jh(t);let r=by(),o=gy(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=J(n,i.modelCaseConvention);r.$annotations[a]=t[n];return}let s=J(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=J(n,i.modelCaseConvention);r[s]=null;}})),r}async function Ar(i,t,e){return (await Promise.all(t.map(async o=>await ve(i,o,e)))).filter(o=>o!==null)}var Or=class{constructor(t,e,r,o=false){this.model=t,this.idObject={},this.whereObject={},this.logs=o,this.session,this.mongoDataSource=e,e.isConnected&&this.initCollection();}initCollection(){this.collection=this.mongoDataSource.getCurrentConnection().db().collection(this.model.collection);}async ensureInitialized(){await this.mongoDataSource.ensureConnected(),this.collection||this.initCollection();}async one(t={throwErrorOnNull:false}){await this.ensureInitialized(),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,session:this.session}),o=await ve(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:(await(this.model.afterFetch?.([o])??[o]))[0]}async oneOrFail(t={throwErrorOnNull:true}){let e=await this.one(t);if(!e)throw new g("MongoQueryBuilder::oneOrFail","ROW_NOT_FOUND");return e}async many(t={}){await this.ensureInitialized(),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 Ar(this.model,r,this.selectFields);return t.ignoreHooks?.includes("afterFetch")?o:await(this.model.afterFetch?.(o)??o)}async insert(t,e={}){await this.ensureInitialized(),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 ve(this.model,o,this.selectFields)}async insertMany(t,e={}){await this.ensureInitialized(),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 Ar(this.model,o,this.selectFields)}async update(t,e={}){if(await this.ensureInitialized(),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 Ar(this.model,o,this.selectFields)}async delete(t={}){await this.ensureInitialized(),t.ignoreHooks||this.model.beforeDelete?.(this),await this.collection.deleteMany(this.whereObject,{session:this.session});}async count(t={}){return await this.ensureInitialized(),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=ee("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=ee("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=ee("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=ee("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=ee("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=ee("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=ee("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=ee("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=ee("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 R.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 R.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 R.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 R.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 R.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 R.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=ee("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=ee("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=ee("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=ee("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=ee("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=ee("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 xr=class{constructor(t,e,r,o=false){this.logs=o,this.session=r,this.mongoDataSource=e,this.collection=t,e.isConnected&&this.initConnection();}initConnection(){this.mongoClient=this.mongoDataSource.getCurrentConnection(),this.collectionInstance=this.mongoClient.db().collection(this.collection.collection);}async ensureInitialized(){await this.mongoDataSource.ensureConnected(),this.collectionInstance||this.initConnection();}async find(t){await this.ensureInitialized();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){await this.ensureInitialized();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){await this.ensureInitialized();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 g("CollectionManager::findOneOrFail No record found","ROW_NOT_FOUND");return r}query(){return new Or(this.collection,this.mongoDataSource,this.session,this.logs)}async insert(t,e={}){await this.ensureInitialized(),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 ve(this.collection,n)}async insertMany(t,e={}){await this.ensureInitialized(),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 ve(this.collection,s)))}async updateRecord(t){await this.ensureInitialized();let e=t.id;if(!e)throw new g("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 g("CollectionManager::updateRecord","ROW_NOT_FOUND");let n=await this.collectionInstance.findOne({_id:new r.ObjectId(e)},{session:this.session});return await ve(this.collection,n)}async deleteRecord(t){await this.ensureInitialized();let e=t.id;if(!e)throw new g("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 Wl=class extends dt{constructor(e){super({type:"mongo",url:e?.url,logs:e?.logs});this.mongoClient=null;this.connecting=null;this.isConnected=false,this.mongoOptions=e?.options,this.lazyLoad=e?.lazyLoad??false,this.url||(this.url=E.MONGO_URL);}async connect(){if(!this.url)throw new g("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 e=(await ce.getDriver("mongo")).client;this.mongoClient=new e.MongoClient(this.url,this.mongoOptions),await this.mongoClient.connect(),this.isConnected=true;}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new g("MongoDataSource::ensureConnected","CONNECTION_NOT_ESTABLISHED");this.connecting||(this.connecting=this.connect().finally(()=>{this.connecting=null;})),await this.connecting;}}getCurrentConnection(){if(!this.mongoClient)throw new g("MongoDataSource::getCurrentConnection mongo database connection not established","CONNECTION_NOT_ESTABLISHED");return this.mongoClient}startSession(){if(!this.mongoClient)throw new g("MongoDataSource::startSession mongo database connection not established","CONNECTION_NOT_ESTABLISHED");let e=this.mongoClient.startSession();return e.startTransaction(),e}async disconnect(){this.mongoClient&&await this.mongoClient.close(),this.isConnected=false;}async closeConnection(){await this.disconnect();}from(e,r){if(!this.isConnected&&!this.lazyLoad)throw new g("MongoDataSource::from","CONNECTION_NOT_ESTABLISHED");if(typeof e=="string"){let o={_collection:e,collection:e,beforeInsert:void 0,beforeFetch:void 0,beforeUpdate:void 0,beforeDelete:void 0,afterFetch:void 0};return this.getModelManager(o,this).query()}return this.getModelManager(e,this,r?.session)}getModelManager(e,r,o){return new xr(e,r,o,this.logs)}async ping(){let e=Date.now();try{return await this.ensureConnected(),this.mongoClient?(await this.mongoClient.db().command({ping:1}),{ok:!0,latencyMs:Date.now()-e,dialect:"mongo"}):{ok:!1,latencyMs:Date.now()-e,dialect:"mongo"}}catch{return {ok:false,latencyMs:Date.now()-e,dialect:"mongo"}}}async isHealthy(){try{return (await this.ping()).ok}catch{return false}}};var jl=class i{constructor(t){this.OK="OK";this.ioRedisConnection=null;this.connecting=null;this.isConnected=false,this.inputOptions=t||{},this.lazyLoad=t?.lazyLoad??false;}get ioredis(){if(!this.ioRedisConnection)throw new g("RedisDataSource::ioredis connection not established","CONNECTION_NOT_ESTABLISHED");return this.ioRedisConnection}async connect(){if(this.isConnected)return;let t=this.inputOptions.port||+E.REDIS_PORT||6379,e=await import('ioredis').catch(()=>{throw new k("ioredis")});this.ioRedisConnection=new e.default({host:this.inputOptions.host||E.REDIS_HOST,username:this.inputOptions.username||E.REDIS_USERNAME,port:t,password:this.inputOptions.password||E.REDIS_PASSWORD,...this.inputOptions});try{await this.ioRedisConnection.ping(),this.isConnected=!0;}catch{throw new g("RedisDataSource::connect","CONNECTION_NOT_ESTABLISHED")}}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new g("RedisDataSource::ensureConnected","CONNECTION_NOT_ESTABLISHED");this.connecting||(this.connecting=this.connect().finally(()=>{this.connecting=null;})),await this.connecting;}}async set(t,e,r){await this.ensureConnected(),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.ioredis.setex(t,r,e);return}await this.ioredis.set(t,e);}catch{throw new g("RedisDataSource::set","SET_FAILED")}}async get(t){try{let e=await this.ioredis.get(t);return i.getValue(e)}catch{throw new g("RedisDataSource::get","GET_FAILED")}}async getBuffer(t){await this.ensureConnected();try{return await this.ioredis.getBuffer(t)}catch{throw new g("RedisDataSource::getBuffer","GET_FAILED")}}async consume(t){try{let e=await this.ioredis.get(t);return await this.ioredis.del(t),i.getValue(e)}catch{throw new g("RedisDataSource::consume","GET_FAILED")}}async delete(t){await this.ensureConnected();try{await this.ioredis.del(t);}catch{throw new g("RedisDataSource::delete","DELETE_FAILED")}}async flushAll(){await this.ensureConnected();try{await this.ioredis.flushall();}catch{throw new g("RedisDataSource::flushAll","FLUSH_FAILED")}}async disconnect(t){if(!(!this.isConnected||!this.ioRedisConnection))try{await this.ioRedisConnection.quit(),this.isConnected=!1,this.ioRedisConnection=null;}catch{if(t)throw new g("RedisDataSource::disconnect","DISCONNECT_FAILED");R.warn("RedisDataSource::disconnect DISCONNECT_FAILED");}}async lpush(t,...e){await this.ensureConnected();try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioredis.lpush(t,...r)}catch{throw new g("RedisDataSource::lpush","LPUSH_FAILED")}}async rpush(t,...e){await this.ensureConnected();try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioredis.rpush(t,...r)}catch{throw new g("RedisDataSource::rpush","RPUSH_FAILED")}}async lpop(t){try{let e=await this.ioredis.lpop(t);return i.getValue(e)}catch{throw new g("RedisDataSource::lpop","LPOP_FAILED")}}async rpop(t){try{let e=await this.ioredis.rpop(t);return i.getValue(e)}catch{throw new g("RedisDataSource::rpop","RPOP_FAILED")}}async lrange(t,e,r){try{return (await this.ioredis.lrange(t,e,r)).map(n=>i.getValue(n)).filter(n=>n!==null)}catch{throw new g("RedisDataSource::lrange","LRANGE_FAILED")}}async llen(t){await this.ensureConnected();try{return await this.ioredis.llen(t)}catch{throw new g("RedisDataSource::llen","LLEN_FAILED")}}async hset(t,e,r){await this.ensureConnected();try{return typeof r=="object"&&!Buffer.isBuffer(r)&&(r=JSON.stringify(r)),typeof r=="boolean"&&(r=r.toString()),await this.ioredis.hset(t,e,r)}catch{throw new g("RedisDataSource::hset","HSET_FAILED")}}async hmset(t,e){await this.ensureConnected();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.ioredis.hmset(t,r)}catch{throw new g("RedisDataSource::hmset","HMSET_FAILED")}}async hget(t,e){try{let r=await this.ioredis.hget(t,e);return i.getValue(r)}catch{throw new g("RedisDataSource::hget","HGET_FAILED")}}async hgetall(t){try{let e=await this.ioredis.hgetall(t),r={};for(let[o,n]of Object.entries(e))r[o]=i.getValue(n);return r}catch{throw new g("RedisDataSource::hgetall","HGETALL_FAILED")}}async hmget(t,...e){try{return (await this.ioredis.hmget(t,...e)).map(o=>i.getValue(o))}catch{throw new g("RedisDataSource::hmget","HMGET_FAILED")}}async hdel(t,...e){await this.ensureConnected();try{return await this.ioredis.hdel(t,...e)}catch{throw new g("RedisDataSource::hdel","HDEL_FAILED")}}async hexists(t,e){await this.ensureConnected();try{return await this.ioredis.hexists(t,e)}catch{throw new g("RedisDataSource::hexists","HEXISTS_FAILED")}}async hkeys(t){await this.ensureConnected();try{return await this.ioredis.hkeys(t)}catch{throw new g("RedisDataSource::hkeys","HKEYS_FAILED")}}async hlen(t){await this.ensureConnected();try{return await this.ioredis.hlen(t)}catch{throw new g("RedisDataSource::hlen","HLEN_FAILED")}}async sadd(t,...e){await this.ensureConnected();try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioredis.sadd(t,...r)}catch{throw new g("RedisDataSource::sadd","SADD_FAILED")}}async smembers(t){try{return (await this.ioredis.smembers(t)).map(r=>i.getValue(r)).filter(r=>r!==null)}catch{throw new g("RedisDataSource::smembers","SMEMBERS_FAILED")}}async srem(t,...e){await this.ensureConnected();try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioredis.srem(t,...r)}catch{throw new g("RedisDataSource::srem","SREM_FAILED")}}async sismember(t,e){await this.ensureConnected();try{return typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString()),await this.ioredis.sismember(t,e)}catch{throw new g("RedisDataSource::sismember","SISMEMBER_FAILED")}}async scard(t){await this.ensureConnected();try{return await this.ioredis.scard(t)}catch{throw new g("RedisDataSource::scard","SCARD_FAILED")}}async sinter(...t){try{return (await this.ioredis.sinter(...t)).map(r=>i.getValue(r)).filter(r=>r!==null)}catch{throw new g("RedisDataSource::sinter","SINTER_FAILED")}}async sunion(...t){try{return (await this.ioredis.sunion(...t)).map(r=>i.getValue(r)).filter(r=>r!==null)}catch{throw new g("RedisDataSource::sunion","SUNION_FAILED")}}async sdiff(...t){try{return (await this.ioredis.sdiff(...t)).map(r=>i.getValue(r)).filter(r=>r!==null)}catch{throw new g("RedisDataSource::sdiff","SDIFF_FAILED")}}async zadd(t,e,r){await this.ensureConnected();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.ioredis.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.ioredis.zadd(t,...o)}throw new Error("Invalid arguments for zadd")}catch{throw new g("RedisDataSource::zadd","ZADD_FAILED")}}async zrange(t,e,r,o=false){try{let n;if(o){n=await this.ioredis.zrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=i.getValue(n[a]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}return s}return n=await this.ioredis.zrange(t,e,r),n.map(s=>i.getValue(s)).filter(s=>s!==null)}catch{throw new g("RedisDataSource::zrange","ZRANGE_FAILED")}}async zrevrange(t,e,r,o=false){try{let n;if(o){n=await this.ioredis.zrevrange(t,e,r,"WITHSCORES");let s=[];for(let a=0;a<n.length;a+=2){let l=i.getValue(n[a]),u=Number(n[a+1]);l!==null&&s.push({value:l,score:u});}return s}return n=await this.ioredis.zrevrange(t,e,r),n.map(s=>i.getValue(s)).filter(s=>s!==null)}catch{throw new g("RedisDataSource::zrevrange","ZREVRANGE_FAILED")}}async zrem(t,...e){await this.ensureConnected();try{let r=e.map(o=>typeof o=="object"&&!Buffer.isBuffer(o)?JSON.stringify(o):typeof o=="boolean"?o.toString():o);return await this.ioredis.zrem(t,...r)}catch{throw new g("RedisDataSource::zrem","ZREM_FAILED")}}async zscore(t,e){await this.ensureConnected();try{typeof e=="object"&&!Buffer.isBuffer(e)&&(e=JSON.stringify(e)),typeof e=="boolean"&&(e=e.toString());let r=await this.ioredis.zscore(t,e);return r!==null?Number(r):null}catch{throw new g("RedisDataSource::zscore","ZSCORE_FAILED")}}async zcard(t){await this.ensureConnected();try{return await this.ioredis.zcard(t)}catch{throw new g("RedisDataSource::zcard","ZCARD_FAILED")}}async subscribe(t,e){await this.ensureConnected();try{await this.ioredis.subscribe(...t),this.ioredis.on("message",e);}catch{throw new g("RedisDataSource::subscribe","SUBSCRIBE_FAILED")}}async unsubscribe(...t){await this.ensureConnected();try{await this.ioredis.unsubscribe(...t);}catch{throw new g("RedisDataSource::unsubscribe","UNSUBSCRIBE_FAILED")}}async publish(t,e){await this.ensureConnected();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.ioredis.publish(t,r)}catch{throw new g("RedisDataSource::publish","PUBLISH_FAILED")}}async psubscribe(t,e){await this.ensureConnected();try{await this.ioredis.psubscribe(...t),this.ioredis.on("pmessage",(r,o,n)=>{e(o,n);});}catch{throw new g("RedisDataSource::psubscribe","PSUBSCRIBE_FAILED")}}async punsubscribe(...t){await this.ensureConnected();try{await this.ioredis.punsubscribe(...t);}catch{throw new g("RedisDataSource::punsubscribe","PUNSUBSCRIBE_FAILED")}}async exists(t){await this.ensureConnected();try{return await this.ioredis.exists(t)}catch{throw new g("RedisDataSource::exists","EXISTS_FAILED")}}async expire(t,e){await this.ensureConnected();try{return await this.ioredis.expire(t,e)}catch{throw new g("RedisDataSource::expire","EXPIRE_FAILED")}}async expireat(t,e){await this.ensureConnected();try{return await this.ioredis.expireat(t,e)}catch{throw new g("RedisDataSource::expireat","EXPIREAT_FAILED")}}async pexpire(t,e){await this.ensureConnected();try{return await this.ioredis.pexpire(t,e)}catch{throw new g("RedisDataSource::pexpire","PEXPIRE_FAILED")}}async ttl(t){await this.ensureConnected();try{return await this.ioredis.ttl(t)}catch{throw new g("RedisDataSource::ttl","TTL_FAILED")}}async pttl(t){await this.ensureConnected();try{return await this.ioredis.pttl(t)}catch{throw new g("RedisDataSource::pttl","PTTL_FAILED")}}async persist(t){await this.ensureConnected();try{return await this.ioredis.persist(t)}catch{throw new g("RedisDataSource::persist","PERSIST_FAILED")}}async keys(t){await this.ensureConnected();try{return await this.ioredis.keys(t)}catch{throw new g("RedisDataSource::keys","KEYS_FAILED")}}async rename(t,e){await this.ensureConnected();try{return await this.ioredis.rename(t,e)}catch{throw new g("RedisDataSource::rename","RENAME_FAILED")}}async type(t){await this.ensureConnected();try{return await this.ioredis.type(t)}catch{throw new g("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)}};var $r={string:"string",varchar:"string",char:"string",text:"textarea",longtext:"textarea",mediumtext:"textarea",tinytext:"textarea",integer:"number",int:"number",smallint:"number",bigint:"number",tinyint:"number",mediumint:"number",float:"float",double:"float",decimal:"float",numeric:"float",real:"float",boolean:"boolean",bool:"boolean",date:"date",datetime:"datetime",timestamp:"datetime",time:"string",year:"number",json:"mixed",jsonb:"mixed",uuid:"string",ulid:"string",binary:"string",blob:"string",enum:"string"};var Ny=null;function Ve(i,t){return t.getModelManager(i)}function Ty(i,t,e){if(!t||typeof t!="object")return;let r=t;if(!r.filters)return;let o=e.getColumns();for(let[n,s]of Object.entries(r.filters)){let a=s.value;if(a==null||a==="")continue;let l=o.find(m=>m.columnName===n||m.databaseName===n);if(!l)continue;let u=typeof l.type=="string"?l.type:"string",d=$r[u]||"string";if(d==="string"||d==="textarea"){i.whereLike(n,`%${a}%`);continue}if(d==="boolean"){i.where(n,a==="true"||a===true);continue}if(d==="date"||d==="datetime"){if(typeof a=="object"&&a!==null){let m=a;m.from&&i.where(n,">=",m.from),m.to&&i.where(n,"<=",m.to);continue}i.where(n,a);continue}i.where(n,a);}}function $t(i,t){let e={},r=t.getColumns();for(let o of r){let n=i[o.columnName];e[o.columnName]=n;}return e}async function Hh(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),{BaseResource:t,BaseRecord:e,BaseProperty:r}=i;return class extends t{constructor(n){super(n),this._model=n,this._db=Ny;}static isAdapterFor(n){if(typeof n!="function")return false;let s=n;return s.prototype!==void 0&&typeof s.table=="string"&&typeof s.getColumns=="function"}databaseName(){return this._db.database||"hysteria"}databaseType(){return this._db.getDbType()}id(){return this._model.table}properties(){return this._model.getColumns().map(s=>{let a=typeof s.type=="string"?s.type:"string",l=$r[a]||"string";return new r({path:s.columnName,type:l,isId:s.isPrimary,isSortable:true})})}property(n){let a=this._model.getColumns().find(d=>d.columnName===n||d.databaseName===n);if(!a)return null;let l=typeof a.type=="string"?a.type:"string",u=$r[l]||"string";return new r({path:a.columnName,type:u,isId:a.isPrimary,isSortable:true})}async count(n){let a=Ve(this._model,this._db).query();return Ty(a,n,this._model),a.getCount()}async find(n,s={}){let l=Ve(this._model,this._db).query();return Ty(l,n,this._model),s.limit&&l.limit(s.limit),s.offset&&l.offset(s.offset),s.sort?.sortBy&&l.orderBy(s.sort.sortBy,s.sort.direction||"asc"),(await l.many()).map(d=>new e($t(d,this._model),this))}async findOne(n){if(!this._model.primaryKey)return null;let l=await Ve(this._model,this._db).findOneByPrimaryKey(n);return l?new e($t(l,this._model),this):null}async findMany(n){let s=this._model.primaryKey;return s?(await Ve(this._model,this._db).query().whereIn(s,n).many()).map(u=>new e($t(u,this._model),this)):[]}async create(n){let a=await Ve(this._model,this._db).insert(n,{returning:["*"]});return $t(a,this._model)}async update(n,s){if(!this._model.primaryKey)throw new Error("Model has no primary key");let l=Ve(this._model,this._db);if(!await l.findOneByPrimaryKey(n))throw new Error("Record not found");let d=await l.updateRecord(n,s,{returning:["*"]});return $t(d,this._model)}async delete(n){if(!this._model.primaryKey)throw new Error("Model has no primary key");let a=Ve(this._model,this._db);await a.findOneByPrimaryKey(n)&&await a.deleteRecord(n);}}}async function zh(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),{BaseDatabase:t}=i;return class extends t{static isAdapterFor(r){return false}resources(){return []}}}async function Yh(){let i=await import('adminjs').catch(()=>{throw new k("adminjs")}),t=await Hh(),e=await zh();i.default.registerAdapter({Database:e,Resource:t});}async function Fl(i,t){Ny=i;let e=await import('adminjs').catch(()=>{throw new k("adminjs")});await Yh();let r=t.resources||Object.values(i.models);if(!r.length)throw new Error("No models provided for AdminJS. Please provide models in the resources option or register them in SqlDataSource.");let o=r.map(a=>{let l=t.resourceOptions?.[a.table]||{};return {resource:a,options:l}}),n={rootPath:t.rootPath||"/admin",resources:o};if(t.branding&&(n.branding=t.branding),t.locale?.language&&(n.locale=t.locale),t.assets&&(n.assets=t.assets),t.settings&&(n.settings=t.settings),t.pages){let a={};for(let[l,u]of Object.entries(t.pages))u.component&&(a[l]=u);Object.keys(a).length>0&&(n.pages=a);}return {admin:new e.default(n)}}async function wy(i,t){let{admin:e}=await Fl(i,t),r;try{r=await import('@adminjs/express');}catch{throw new k("@adminjs/express")}let o=r.buildRouter(e);return {admin:e,router:o}}var Gh=i=>{let{required:t,...e}=i.openApi||{},r={...e,type:i.openApi?.type||"string",description:i.openApi?.description??`Property: ${i.columnName}`};return i.openApi?.type?{...r,type:i.openApi.type}:Array.isArray(i.type)?{...r,type:"string",enum:i.type}:i.type==="date"||i.type==="datetime"||i.type==="timestamp"||i.type==="time"?{...r,type:"string",format:"date-time"}:i.type==="boolean"?{...r,type:"boolean"}:i.type==="integer"||i.type==="tinyint"||i.type==="smallint"||i.type==="mediumint"||i.type==="increment"?{...r,type:"integer",format:"int32"}:i.type==="biginteger"||i.type==="bigIncrement"?{...r,type:"integer",format:"int64"}:i.type==="float"||i.type==="real"?{...r,type:"number",format:"float"}:i.type==="double"?{...r,type:"number",format:"double"}:i.type==="decimal"||i.type==="numeric"?{...r,type:"number"}:i.type==="json"||i.type==="jsonb"?{...r,type:"object"}:i.type==="uuid"?{...r,type:"string",format:"uuid"}:i.type==="ulid"?{...r,type:"string",format:"ulid"}:i.type==="string"||i.type==="char"||i.type==="varchar"||i.type==="text"||i.type==="longtext"||i.type==="mediumtext"||i.type==="tinytext"?{...r,type:"string"}:i.type==="blob"||i.type==="binary"||i.type==="varbinary"||i.type==="tinyblob"||i.type==="mediumblob"||i.type==="longblob"?{...r,type:"string",format:"binary"}:i.type==="year"?{...r,type:"integer",format:"int32"}:r},Zh=i=>i.openApi?.required??false,Xh=i=>{let t=i.getColumns(),e={};for(let r of t)r.openApi?.excludeFromSwagger||(e[r.columnName]=Gh(r));return e},eg=i=>{let t=i.getColumns(),e=[];for(let r of t)Zh(r)&&e.push(r.columnName);return e||[]},Ul=i=>{let t=Xh(i),e=eg(i);return {type:"object",properties:t,required:e.length?e:[]}},ik=i=>i.map(t=>Ul(t)),ak=i=>Ul(i),Sy=i=>i.map(t=>({...Ul(t),modelName:t.table,$id:t.table}));var Vl=(i,t)=>{let e=Re__default.default.createHash("sha256"),r=i;return e.update(r),e.digest("hex")};var Dr=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="check_constraint_info";this.table=e;}};var Ir=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="foreign_key_info";this.table=e;}};var Er=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="index_info";this.table=e;}};var Pr=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="primary_key_info";this.table=e;}};var vr=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="table_info";this.table=e;}};var Br=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_table";this.table=e;}};var Qr=class extends w{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_column";this.table=e,this.column=r;}};var Kr=class extends w{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_index";this.table=e,this.index=r;}};var kr=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_primary_key";this.table=e;}};var Lr=class extends w{constructor(e,r){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="has_check_constraint";this.table=e,this.constraint=r;}};var Wr=class extends w{constructor(){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="get_tables";}};var jr=class extends w{constructor(e){super("schema");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=false;this.folder="schema";this.file="get_column_listing";this.table=e;}};var Be=class{constructor(t){this.nodes=t;}getNodes(){return this.nodes}};var Fr=class extends w{constructor(e){super("");this.chainsWith=" ";this.canKeywordBeSeenMultipleTimes=true;this.folder="constraint";this.file="after";this.column=e;}};var Ur=class extends Be{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=fe(this.tableName,S(this.columnNode.column));return this.context==="alter_table"?(this.nodes.push(new H("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this):this.sqlType==="sqlite"?this.handleSqliteAutoIncrement(t||{constraintName:e}):(this.namedConstraints.push(new H("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??e})),this)}foreignKey(t,e){let[r,o]=t.split("."),n=o.split(","),s=e?.constraintName??Y(this.tableName??"",S(this.columnNode.column),n[0]);return this.context==="alter_table"?(this.nodes.push(new H("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this):(this.namedConstraints.push(new H("foreign_key",{columns:[S(this.columnNode.column)],references:{table:r,columns:n},constraintName:s,onDelete:e?.onDelete,onUpdate:e?.onUpdate})),this)}increment(){return this.columnNode.autoIncrement=true,this}unsigned(){return this.columnNode.unsigned=true,this}zerofill(){return this.columnNode.zerofill=true,this}notNullable(){return this.nodes.push(new H("not_null",{columns:[S(this.columnNode.column)]})),this}nullable(){return this.nodes.push(new H("null",{columns:[S(this.columnNode.column)]})),this}default(t){let e;return t instanceof I?e=t:t===null?e="NULL":typeof t=="boolean"?e=t?"TRUE":"FALSE":t!==void 0&&(e=t.toString()),this.nodes.push(new H("default",{defaultValue:e})),this}unique(t){return this.context==="alter_table"?(this.nodes.push(new H("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName??ae(this.tableName??"",S(this.columnNode.column))})),this):(this.namedConstraints.push(new H("unique",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName||ae(this.tableName??"",S(this.columnNode.column))})),this)}check(t,e){let r=S(this.columnNode.column),o=e?.constraintName??`chk_${this.tableName}_${r}`.substring(0,63);return this.context==="alter_table"?(this.nodes.push(new H("check",{columns:[r],checkExpression:t,constraintName:o})),this):(this.namedConstraints.push(new H("check",{columns:[r],checkExpression:t,constraintName:o})),this)}after(t){return this.sqlType!=="mysql"?this:(this.nodes.push(new Fr(t)),this)}collate(t){return this.columnNode.collate=t,this}handleSqliteAutoIncrement(t){return this.nodes.push(new H("primary_key",{columns:[S(this.columnNode.column)],constraintName:t?.constraintName,autoIncrement:this.columnNode.autoIncrement,columnType:"integer"})),this}};var Je=class extends Be{constructor(e,r,o,n){super(r);this.context="create_table";this.tableName=o,this.namedConstraints=[],this.context=n??"create_table",this.sqlType=e;}mysqlOptions(e){return this._mysqlOptions=e,this}getMysqlOptions(){return this._mysqlOptions}build(e){return this.nodes.push(e),new Ur(this.sqlType,this.nodes,e,this.tableName,this.namedConstraints,this.context)}rawStatement(e){return new I(e)}char(e,r=1){let o=new B(e,"char",{length:r});return this.build(o)}varchar(e,r=255){let o=new B(e,"varchar",{length:r});return this.build(o)}string(e,r=255){return this.varchar(e,r)}text(e,r="longtext"){let o=new B(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 B(e,"uuid");return this.build(r)}ulid(e){let r=new B(e,"ulid");return this.build(r)}integer(e,r=255){let o=new B(e,"integer",{length:r});return this.build(o)}tinyint(e,r=255){let o=new B(e,"tinyint",{length:r});return this.build(o)}smallint(e,r=255){let o=new B(e,"smallint",{length:r});return this.build(o)}mediumint(e,r=255){let o=new B(e,"mediumint",{length:r});return this.build(o)}biginteger(e,r=255){let o=new B(e,"bigint",{length:r});return this.build(o)}bigint(e,r=255){return this.biginteger(e,r)}float(e,r=10){let o=new B(e,"float",{precision:r});return this.build(o)}double(e,r=10){let o=new B(e,"double",{precision:r});return this.build(o)}real(e,r=10){let o=new B(e,"real",{precision:r});return this.build(o)}decimal(e,r=10,o=2){let n=new B(e,"decimal",{precision:r,scale:o});return this.build(n)}numeric(e,r=10,o=2){let n=new B(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 B(e,"date",{precision:r});return this.build(o)}time(e,r){let o=new B(e,"time",{precision:r});return this.build(o)}year(e){let r=new B(e,"year");return this.build(r)}datetime(e,r){let o=new B(e,"datetime",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}timestamp(e,r){let o=new B(e,"timestamp",{withTimezone:r?.withTimezone??false,precision:r?.precision,autoCreate:r?.autoCreate,autoUpdate:r?.autoUpdate});return this.build(o)}boolean(e){let r=new B(e,"boolean");return this.build(r)}binary(e){let r=new B(e,"binary");return this.build(r)}varbinary(e,r=255){let o=new B(e,"varbinary",{length:r});return this.build(o)}blob(e){let r=new B(e,"blob");return this.build(r)}tinyblob(e){let r=new B(e,"tinyblob");return this.build(r)}mediumblob(e){let r=new B(e,"mediumblob");return this.build(r)}longblob(e){let r=new B(e,"longblob");return this.build(r)}json(e){let r=new B(e,"json");return this.build(r)}jsonb(e){let r=new B(e,"jsonb");return this.build(r)}enum(e,r){let o=new B(e,"enum",{enumValues:r});return this.build(o)}custom(e,r,o){let n=new B(e,r,{length:o});return this.build(n)}rawColumn(e){let r=new B(e,"",{isRawValue:true});return this.build(r)}geometry(e){let r=new B(e,"geometry");return this.build(r)}point(e){let r=new B(e,"point");return this.build(r)}linestring(e){let r=new B(e,"linestring");return this.build(r)}polygon(e){let r=new B(e,"polygon");return this.build(r)}multiPoint(e){let r=new B(e,"multiPoint");return this.build(r)}getNamedConstraints(){return this.namedConstraints}};var Vr=class extends Be{constructor(t,e,r){super(e),this.table=t,this.sqlType=r;}rawStatement(t){return new I(t)}addColumn(t){let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=r.getNamedConstraints(),s=e.filter(m=>m.folder==="column");if(e=e.concat(n),s.length!==1)throw new Error("addColumn callback must define exactly one column");let a=s[0],l=o.getNodes().filter(m=>{let c=m;return c.constraintType==="not_null"||c.constraintType==="null"||c.constraintType==="default"}),u=new Zt(a);u.inlineConstraints=l,this.nodes.push(u),o.getNodes().filter(m=>{let c=m;return c.constraintType==="unique"||c.constraintType==="foreign_key"||c.constraintType==="primary_key"}).forEach(m=>{this.nodes.push(new ge(m));});}alterColumn(t){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let e=[],r=new Je(this.sqlType,e,this.table,"alter_table"),o=t(r);if(!e.length)return;let n=e.filter(p=>p.folder==="column");if(n.length!==1)throw new Error("alterColumn callback must define exactly one column");let s=n[0],a=S(s.column),l=o.getNodes().find(p=>p.constraintType==="null"),d=o.getNodes().find(p=>p.constraintType==="not_null")||l,m=o.getNodes().find(p=>p.constraintType==="default"),c={};d&&(c.nullable=d.constraintType==="null"),m&&(m.defaultValue===void 0||m.defaultValue===null||m.defaultValue==="NULL"?c.dropDefault=true:c.default=m.defaultValue),s.collate&&(this.sqlType==="mysql"||this.sqlType==="mariadb")&&(c.collate=s.collate),this.nodes.push(new Xt(S(a),s,c)),d&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(d.constraintType==="not_null"?this.nodes.push(new nr(S(a))):d.constraintType==="null"&&this.nodes.push(new tr(S(a)))),m&&this.sqlType!=="mysql"&&this.sqlType!=="mariadb"&&(m.defaultValue===void 0||m.defaultValue===null||m.defaultValue==="NULL"?this.nodes.push(new wt(S(a))):this.nodes.push(new or(S(a),m.defaultValue))),o.getNodes().forEach(p=>{let f=p;switch(f.constraintType){case "primary_key":this.addPrimaryKey(S(a));break;case "unique":this.unique(S(a),{constraintName:f.constraintName});break;case "foreign_key":this.foreignKey(S(a),f.references?.table??"",S(f.references?.columns?.[0]??""),{constraintName:f.constraintName,onDelete:f.onDelete,onUpdate:f.onUpdate});break}});}dropColumn(t){this.nodes.push(new er(t));}renameColumn(t,e){this.nodes.push(new rr(t,e));}dropDefault(t){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new wt(t));}addPrimaryKey(t){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new st([t]));}addConstraint(...t){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ge(new H(...t)));}foreignKey(t,e,r,o){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ge(new H("foreign_key",{columns:[t],references:{table:e,columns:[r]},constraintName:o?.constraintName??Y(this.table,t,r),onDelete:o?.onDelete,onUpdate:o?.onUpdate})));}unique(t,e){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::alterColumn","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new ge(new H("unique",{columns:[t],constraintName:e?.constraintName??ae(this.table,t)})));}dropForeignKey(t,e){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));let r=Y(this.table,t,e);this.nodes.push(new be(r));}dropUnique(t,e){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::dropUnique","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="cockroachdb")throw new g("AlterTableBuilder::dropUnique","COCKROACHDB_NOT_SUPPORTED",new Error("cockroachdb does not support alter table statements"));let r=e?.constraintName??ae(this.table,t);this.nodes.push(new be(r));}dropConstraint(t){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::dropConstraint","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));this.nodes.push(new be(t));}dropPrimaryKey(t){if(this.sqlType==="sqlite")throw new g("AlterTableBuilder::dropPrimaryKey","SQLITE_NOT_SUPPORTED",new Error("sqlite does not support alter table statements"));if(this.sqlType==="postgres"&&!t)throw new g("AlterTableBuilder::dropPrimaryKey","POSTGRES_TABLE_REQUIRED",new Error("postgres requires the table name"));this.nodes.push(new it(t));}setTableOptions(t){let e=this.sqlType==="mysql"||this.sqlType==="mariadb",r=this.sqlType==="postgres"||this.sqlType==="cockroachdb",o=this.sqlType==="mssql",n=this.sqlType==="oracledb";return this.sqlType==="sqlite"?this:(e?this.nodes.push(new We(t)):r?this.nodes.push(new We(t)):o?this.nodes.push(new We(t)):n&&this.nodes.push(new We(t)),this)}};var oe=class{constructor(t){if(this.sqlType=t||E.DB_TYPE,!this.sqlType)throw new g("Schema::constructor","ENV_NOT_SET",new Error("env not set, please set DB_TYPE in .env file"));this.queryStatements=[];}rawStatement(t){return new I(t)}rawQuery(t){this.queryStatements.push(t);}async execute(){for(let t of this.queryStatements)this.rawQuery(t);}runFile(t){if(!eo__default.default.existsSync(t))throw new g("Schema::runFile","FILE_NOT_FOUND_OR_NOT_ACCESSIBLE");let e=pt__default.default.basename(t),r=pt__default.default.extname(e);if(r!==".sql"&&r!==".txt")throw new g("Schema::runFile","FILE_NOT_A_SQL_OR_TXT_FILE");let n=eo__default.default.readFileSync(t,"utf-8").split(";").map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("--"));for(let s of n)this.rawQuery(s);}createTable(t,e,r){let o=new Je(this.sqlType,[],t);e(o);let n=o.getNodes(),s=new N({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"},this.sqlType),a={...r,...this.sqlType==="mysql"||this.sqlType==="mariadb"?o.getMysqlOptions()||{}:{}},l=new sr(t,n,o.getNamedConstraints(),r?.ifNotExists,a),u=s.parse([l]).sql,d=u.startsWith("create table")?u:`create table ${u}`;this.rawQuery(d),this.generateAutoUpdateTriggers(t,n);}alterTable(t,e){let r=[],o=new Vr(t,r,this.sqlType);if(e(o),!r.length)return;let n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"}),s=[],a=()=>{if(!s.length)return;let u=new de(t,s),d=n.parse([u]).sql;if(!d||!d.trim())return;let m=d.startsWith("alter table")?d:`alter table ${d}`;this.rawQuery(m),s=[];};for(let u of r)u.file==="add_constraint"&&s.length&&s[0].file==="add_column"||a(),s.push(u);a();let l=r.filter(u=>u.file==="add_column").map(u=>u.column);this.generateAutoUpdateTriggers(t,l);}dropTable(t,e=false){let r=new ir(t,e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}renameTable(t,e){let r=new de(t,[new Ye(e)]),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}truncateTable(t){let e=new lt(t,true),r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}createIndex(t,e,r={}){Array.isArray(e)||(e=[e]);let o=r.constraintName||Ut(t,e.join("_")),n=new lr(t,e,o),s=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(s.parse([n]).sql);}dropIndex(t,e){let r=new ur(t,e),o=this.generateAstInstance({table:e,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addPrimaryKey(t,e){let r=new de(t,[new st(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??ae(t,o.join("_")),s=new H("unique",{columns:o,constraintName:n}),a=new de(t,[new ge(s)]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropForeignKey(t,e,r){let o=Y(t,e,r),n=new be(o),s=new de(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)?ae(t,e.join("_")):ae(t,e),n=r?.constraintName??o,s=new be(n),a=new de(t,[s]),l=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(l.parse([a]).sql);}dropPrimaryKey(t){let e=new it,r=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(r.parse([e]).sql);}addConstraint(t,...e){let r=new H(...e),o=new de(t,[new ge(r)]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}dropConstraint(t,e){let r=new be(e),o=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}addCheck(t,e,r){let o=r?.constraintName??`chk_${t}_custom`.substring(0,63),n=new H("check",{checkExpression:e,constraintName:o}),s=new de(t,[new ge(n)]),a=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(a.parse([s]).sql);}dropCheck(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb"){this.rawQuery(`ALTER TABLE \`${t}\` DROP CHECK \`${e}\``);return}let r=new be(e),o=new de(t,[r]),n=this.generateAstInstance({table:t,databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(n.parse([o]).sql);}createExtension(t,e=true){let r=new ar(t,e),o=this.generateAstInstance({table:"",databaseCaseConvention:"preserve",modelCaseConvention:"preserve"});this.rawQuery(o.parse([r]).sql);}generateAutoUpdateTriggers(t,e){if(this.sqlType==="mysql"||this.sqlType==="mariadb")return;let r=e.filter(o=>o.folder==="column"&&o.autoUpdate===true).map(o=>S(o.column));for(let o of r){let n=this.getAutoUpdateTriggerSql(t,o);for(let s of n)this.rawQuery(s);}}getAutoUpdateTriggerSql(t,e){let r=`trg_${t}_${e}_auto_update`;switch(this.sqlType){case "postgres":case "cockroachdb":return [`CREATE OR REPLACE FUNCTION ${r}_fn() RETURNS trigger AS $$ BEGIN NEW."${e}" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql`,`CREATE OR REPLACE TRIGGER ${r} BEFORE UPDATE ON "${t}" FOR EACH ROW EXECUTE FUNCTION ${r}_fn()`];case "sqlite":return [`CREATE TRIGGER IF NOT EXISTS ${r} AFTER UPDATE ON "${t}" FOR EACH ROW BEGIN UPDATE "${t}" SET "${e}" = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid; END`];case "mssql":return [`CREATE OR ALTER TRIGGER [${r}] ON [${t}] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE t SET t.[${e}] = CURRENT_TIMESTAMP FROM [${t}] t INNER JOIN inserted i ON t.[id] = i.[id]; END`];case "oracledb":return [`CREATE OR REPLACE TRIGGER "${r}" BEFORE UPDATE ON "${t}" FOR EACH ROW BEGIN :NEW."${e}" := CURRENT_TIMESTAMP; END;`];default:return []}}generateAstInstance(t){return new N(t,this.sqlType)}};var Jr,_y,Dt=class{constructor(t,e){su(this,Jr);this.executionPromise=null;this.state="pending";this.executionError=null;this.dataSource=t,this.schema=new oe(e||t.getDbType());}then(t,e){return this.state==="pending"&&(this.executionPromise=iu(this,Jr,_y).call(this)),this.executionPromise.then(t,e)}rawStatement(t){return this.schema.rawStatement(t)}rawQuery(t){return this.schema.rawQuery(t),this}createTable(t,e,r){return this.schema.createTable(t,e,r),this}alterTable(t,e){return this.schema.alterTable(t,e),this}dropTable(t,e=false){return this.schema.dropTable(t,e),this}renameTable(t,e){return this.schema.renameTable(t,e),this}truncateTable(t){return this.schema.truncateTable(t),this}createIndex(t,e,r){return this.schema.createIndex(t,e,r),this}dropIndex(t,e){return this.schema.dropIndex(t,e),this}addPrimaryKey(t,e){return this.schema.addPrimaryKey(t,e),this}addUnique(t,e,r){return this.schema.addUnique(t,e,r),this}addConstraint(t,e,...r){return this.schema.addConstraint(t,e,...r),this}dropPrimaryKey(t){return this.schema.dropPrimaryKey(t),this}dropForeignKey(t,e,r){return this.schema.dropForeignKey(t,e,r),this}dropUnique(t,e,r){return this.schema.dropUnique(t,e,r),this}dropConstraint(t,e){return this.schema.dropConstraint(t,e),this}createExtension(t,e=true){return this.schema.createExtension(t,e),this}toQuery(){let t=this.schema.queryStatements;return t.length===1?t[0]:t}toQueries(){return [...this.schema.queryStatements]}toString(){let t=this.schema.queryStatements;return t.length===1?t[0]||"":t.join(`;
193
193
  `)}async execute(){if(this.state!=="executed"){if(this.state==="failed")throw this.executionError;return this.then()}}isExecuted(){return this.state==="executed"}isPending(){return this.state==="pending"}hasFailed(){return this.state==="failed"}async hasTable(t){return this.dataSource.hasTable(t)}async hasColumn(t,e){return this.dataSource.hasColumn(t,e)}async hasColumns(t,...e){return this.dataSource.hasColumns(t,...e)}async hasIndex(t,e){return this.dataSource.hasIndex(t,e)}async hasPrimaryKey(t){return this.dataSource.hasPrimaryKey(t)}async hasUnique(t,e){return this.dataSource.hasUnique(t,e)}async hasForeignKey(t,e){return this.dataSource.hasForeignKey(t,e)}async hasCheckConstraint(t,e){return this.dataSource.hasCheckConstraint(t,e)}async getTables(){return this.dataSource.getTables()}async getColumnListing(t){return this.dataSource.getColumnListing(t)}dropTableIfExists(t){return this.schema.dropTable(t,true),this}async dropIndexIfExists(t,e){if(await this.dataSource.hasIndex(e,t)){let o=new oe(this.dataSource.getDbType());o.dropIndex(t,e);let n=o.queryStatements[0];n&&await this.dataSource.rawQuery(n);}}renameColumn(t,e,r){return this.schema.alterTable(t,o=>{o.renameColumn(e,r);}),this}};Jr=new WeakSet,_y=async function(){try{this.state="pending";let t=this.schema.queryStatements;if(!t.length){this.state="executed";return}for(let e of t)await this.dataSource.rawQuery(e);this.state="executed";}catch(t){throw this.state="failed",this.executionError=t,t}};var Hr=class{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}buildDropDependencies(t){let e=new Map,r=new Map,o=new Map;for(let n of t.relationsToDrop||[]){let s=`${n.table}.${n.relation.name}`,a=[];if(n.relation.referencedTable&&a.push(`table.${n.relation.referencedTable}`),n.relation.referencedColumns)for(let l of n.relation.referencedColumns)a.push(`column.${n.relation.referencedTable}.${l}`);e.set(s,a);}for(let n of t.tablesToDrop||[]){let s=`table.${n.table}`,a=[];for(let l of this.models){let u=l.getRelations();for(let d of u)d.type==="belongsTo"&&d.model().table===n.table&&a.push(`fk.${l.table}.${d.constraintName}`);}r.set(s,a);}for(let n of t.columnsToDrop||[]){let s=`column.${n.table}.${n.column}`,a=[],l=this.models.find(u=>u.table===n.table);if(l){let u=l.getColumns().find(d=>d.databaseName===n.column);if(u){u.isPrimary&&a.push(`pk.${n.table}`);let d=l.getRelations();for(let m of d)m.columnName===u.columnName&&a.push(`fk.${n.table}.${m.constraintName}`);}}o.set(s,a);}return {foreignKeys:e,tables:r,constraints:o}}topologicalSortReverse(t,e){let r=new Set,o=new Set,n=[],s=a=>{if(o.has(a))throw new Error(`Circular dependency detected: ${a}`);if(r.has(a))return;o.add(a);let l=e(a);for(let u of l)s(u);o.delete(a),r.add(a),n.push(a);};for(let a of t.keys())r.has(a)||s(a);return n}generateDropOperations(t){let e=this.buildDropDependencies(t),r=[],o=this.topologicalSortReverse(e.foreignKeys,s=>e.foreignKeys.get(s)||[]);for(let s of o){let[a,l]=s.split("."),u=t.relationsToDrop?.find(d=>d.table===a&&d.relation.name===l);u&&r.push({type:"DROP_FOREIGN_KEY",phase:"DESTRUCTIVE_OPERATIONS",table:a,constraint:l,data:u,dependencies:e.foreignKeys.get(s)||[],sqlStatements:this.generateDropForeignKeySql(u)});}let n=this.topologicalSortReverse(e.tables,s=>e.tables.get(s)||[]);for(let s of t.columnsToDrop||[]){let a=`column.${s.table}.${s.column}`,l=e.constraints.get(a)||[];for(let u of l)u.startsWith("pk.")?r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:"PRIMARY KEY",data:{type:"primary_key",table:s.table},dependencies:[a],sqlStatements:this.generateDropPrimaryKeySql(s.table)}):u.startsWith("unique.")&&r.push({type:"DROP_CONSTRAINT",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,constraint:`UNIQUE_${s.column}`,data:{type:"unique",table:s.table,column:s.column},dependencies:[a],sqlStatements:this.generateDropUniqueConstraintSql(s.table,s.column)});}for(let s of t.columnsToDrop||[])r.push({type:"DROP_COLUMN",phase:"DESTRUCTIVE_OPERATIONS",table:s.table,column:s.column,data:s,dependencies:[],sqlStatements:this.generateDropColumnSql(s)});for(let s of n){let a=s.replace("table.",""),l=t.tablesToDrop?.find(u=>u.table===a);l&&r.push({type:"DROP_TABLE",phase:"DESTRUCTIVE_OPERATIONS",table:a,data:l,dependencies:e.tables.get(s)||[],sqlStatements:this.generateDropTableSql(l)});}return r}analyzeConstraintImpact(t){let e=new Map;for(let r of t.columnsToDrop||[]){let o=[],n=this.models.find(s=>s.table===r.table);if(n){let s=n.getColumns().find(a=>a.databaseName===r.column);if(s){s.isPrimary&&o.push(`PRIMARY KEY on ${r.table}`);let a=n.getRelations();for(let l of a)l.columnName===s.columnName&&o.push(`FOREIGN KEY ${l.constraintName} on ${r.table}`);}}e.set(`${r.table}.${r.column}`,o);}return e}detectMixedOperations(t){let e=[];for(let r of t.columnsToModify||[]){let o=this.models.find(n=>n.table===r.table);o&&o.getColumns().find(s=>s.databaseName===r.dbColumns.name)&&this.hasConstraintChanges(r.dbColumns,r.modelColumn)&&e.push({type:"column_modification_with_constraints",table:r.table,column:r.dbColumns.name,description:`Column ${r.dbColumns.name} modification requires constraint recreation`});}for(let r of t.primaryKeysToModify||[])e.push({type:"primary_key_modification",table:r.table,description:`Primary key modification on ${r.table} requires FK recreation`});return e}hasConstraintChanges(t,e){return t.isNullable!==!e.constraints?.nullable||t.isUnique!==!!e.constraints?.unique||t.defaultValue!==e.constraints?.default}generateDropForeignKeySql(t){if(this.sql.getDbType()==="sqlite")return [];if(!t.relation.name)return [];let e=this.sql.schema().alterTable(t.table,o=>{o.dropConstraint(t.relation.name);}).toQueries(),r=this.sql.getDbType();return (r==="mysql"||r==="mariadb")&&e.push(`DROP INDEX \`${t.relation.name}\` ON \`${t.table}\``),e}generateDropPrimaryKeySql(t){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,e=>{e.dropPrimaryKey();}).toQueries()}generateDropUniqueConstraintSql(t,e){return this.sql.getDbType()==="sqlite"?[]:this.sql.schema().alterTable(t,r=>{r.dropConstraint(`UNIQUE_${e}`);}).toQueries()}generateDropColumnSql(t){return this.sql.schema().alterTable(t.table,e=>{e.dropColumn(t.column);}).toQueries()}generateDropTableSql(t){return [`DROP TABLE ${t.table}`]}};var zr=class zr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models),this.dropResolver=new Hr(t);}generateOperations(t){let e=[];e.push(...this.generateStructureCreationOperations(t)),e.push(...this.generateConstraintCreationOperations(t)),e.push(...this.generateDestructiveOperations(t)),e.push(...this.generateColumnModificationOperations(t));let r=l=>l.table&&l.constraint?`${l.table}::${l.constraint}`:void 0,o=new Set(e.filter(l=>l.type==="ADD_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),n=new Set(e.filter(l=>l.type==="DROP_FOREIGN_KEY").map(l=>r(l)).filter(Boolean)),s=new Set([...o].filter(l=>n.has(l)));return e.filter(l=>{let u=r(l);return u?!(s.has(u)&&(l.type==="ADD_FOREIGN_KEY"||l.type==="DROP_FOREIGN_KEY")):true})}generateStructureCreationOperations(t){let e=[];for(let r of t.tablesToAdd){let o=this.sql.schema().createTable(r.table,n=>{for(let s of r.columns){if(Array.isArray(s.type)){n.enum(s.databaseName,s.type);continue}s.type&&this.executeBuilderMethod(r.table,n,s,[s.databaseName,s.length,s.precision&&!s.withTimezone?s.precision:void 0,s.scale,s.withTimezone?{withTimezone:s.withTimezone,precision:s.precision}:void 0].filter(Boolean),true);}}).toQuery();e.push({type:"CREATE_TABLE",phase:"STRUCTURE_CREATION",table:r.table,data:r,dependencies:[],sqlStatements:[o]});}for(let r of t.columnsToAdd){let o=this.generateAddColumnViaAlter(r);e.push({type:"ADD_COLUMN",phase:"STRUCTURE_CREATION",table:r.table,column:r.column.databaseName,data:r,dependencies:[`table.${r.table}`],sqlStatements:o});}return e}generateConstraintCreationOperations(t){let e=[];for(let o of t.uniquesToDrop||[]){let n=this.sql.schema().alterTable(o.table,s=>{s.dropConstraint(o.name);}).toQueries();e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:n});}let r=new Set((t.uniquesToDrop||[]).map(o=>o.name));for(let o of t.indexesToDrop){if(r.has(o.index))continue;let n=new oe(this.sql.getDbType());n.dropIndex(o.index,o.table);let s=n.queryStatements[0];e.push({type:"DROP_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[s]});}for(let o of t.primaryKeysToAdd){let a=this.models.find(u=>u.table===o.table)?.getColumns().find(u=>u.columnName===o.columns[0])?.primaryKeyConstraintName||fe(o.table,o.columns[0]),l=this.sql.schema().alterTable(o.table,u=>{let d=a||fe(o.table,o.columns[0]);u.addConstraint("primary_key",{columns:[o.columns[0]],constraintName:d});}).toQueries();e.push({type:"ADD_PRIMARY_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:a,data:o,dependencies:[`table.${o.table}`],sqlStatements:l});}for(let o of t.relationsToAdd){if(o.relation.type==="manyToMany")continue;let n=this.generateAddRelationViaAlter(o),s=this.computeFkConstraintName(o);e.push({type:"ADD_FOREIGN_KEY",phase:"CONSTRAINT_CREATION",table:o.table,constraint:s,data:o,dependencies:this.getForeignKeyDependencies(o),sqlStatements:n});}for(let o of t.uniquesToAdd||[]){let n=this.models.find(l=>l.table===o.table),s=(o.columns||[]).map(l=>n?.getColumns().find(d=>d.columnName===l)?.databaseName||l),a=this.sql.schema().alterTable(o.table,l=>{l.addConstraint("unique",{columns:s,constraintName:o.name||"mandatory"});}).toQueries();e.push({type:"ADD_UNIQUE_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name||"mandatory",data:o,dependencies:[`table.${o.table}`],sqlStatements:a});}for(let o of t.indexesToAdd){let n=this.generateCreateIndexSql(o);e.push({type:"CREATE_INDEX",phase:"CONSTRAINT_CREATION",table:o.table,index:o.index,data:o,dependencies:[`table.${o.table}`],sqlStatements:[n]});}for(let o of t.checksToDrop||[]){let n=new oe(this.sql.getDbType());n.dropCheck(o.table,o.name);let s=n.queryStatements;e.push({type:"DROP_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}for(let o of t.checksToAdd||[]){let n=new oe(this.sql.getDbType());n.addCheck(o.table,o.expression,{constraintName:o.name});let s=n.queryStatements;e.push({type:"ADD_CHECK_CONSTRAINT",phase:"CONSTRAINT_CREATION",table:o.table,constraint:o.name,data:o,dependencies:[`table.${o.table}`],sqlStatements:s});}return e}computeFkConstraintName(t){let e=S(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=S(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,Y(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=S(t.relation.manyToManyOptions.throughModel);e.push(`table.${o}`);}e.push(`table.${t.table}`);let r=this.models.find(o=>o.table===t.table);if(r){let o=r.getColumns().find(n=>n.columnName===t.relation.columnName||n.databaseName===t.relation.columnName);o&&e.push(`column.${t.table}.${o.databaseName}`);}return e}executeBuilderMethod(t,e,r,o,n=true){let s;if(Array.isArray(r.type))s=e.enum(o[0],r.type);else if(typeof r.type=="string"&&zr.BUILTIN_COLUMN_TYPES.has(r.type))s=e[r.type](...o);else if(typeof r.type=="string")s=e.custom(o[0],r.type,r.length);else throw new Error(`Unknown column type: ${String(r.type)} for column ${r.columnName}`);return n&&(r.isPrimary&&s.primaryKey({constraintName:r.primaryKeyConstraintName||fe(t,r.columnName)}),r.unsigned&&s.unsigned(),r.zerofill&&s.zerofill(),r.constraints?.default!==void 0&&s.default(r.constraints.default),r.constraints?.nullable===false?s.notNullable():r.constraints?.nullable===true&&s.nullable()),s}generateAddColumnViaAlter(t){let e=[t.column.databaseName,t.column.length,t.column.precision&&!t.column.withTimezone?t.column.precision:void 0,t.column.scale,t.column.withTimezone?{withTimezone:t.column.withTimezone,precision:t.column.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,r=>{r.addColumn(o=>{let n=this.executeBuilderMethod(t.table,o,t.column,e,false);return t.column.constraints?.default!==void 0&&n.default(t.column.constraints.default),t.column.constraints?.nullable===false?n.notNullable():t.column.constraints?.nullable===true&&n.nullable(),n});}).toQueries()}generateModifyColumnViaAlter(t){if(this.sql.getDbType()==="sqlite")return [];let e=[t.modelColumn.databaseName,t.modelColumn.length,t.modelColumn.precision&&!t.modelColumn.withTimezone?t.modelColumn.precision:void 0,t.modelColumn.scale,t.modelColumn.withTimezone?{withTimezone:t.modelColumn.withTimezone,precision:t.modelColumn.precision}:void 0].filter(Boolean);return this.sql.schema().alterTable(t.table,o=>{o.alterColumn(n=>{let s=this.executeBuilderMethod(t.table,n,t.modelColumn,e,false);return t.modelColumn.constraints?.default!==void 0?s.default(t.modelColumn.constraints.default):t.dbColumns.defaultValue!=null&&t.dbColumns.defaultValue!==""&&s.default(null),t.modelColumn.constraints?.nullable===false?s.notNullable():t.modelColumn.constraints?.nullable===true&&s.nullable(),s});}).toQueries()}generateCreateIndexSql(t){let e=this.models.find(s=>s.table===t.table),o=(e?.getIndexes().find(s=>s.name===t.index)?.columns||[]).map(s=>e?.getColumns().find(l=>l.columnName===s)?.databaseName||s),n=new oe(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=S(t.relation.manyToManyOptions.throughModel),r=S(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=S(r);if(t.relation.type==="belongsTo"){let c=t.relation.model(),p=c.primaryKey,y=c.getColumns().find(T=>T.columnName===p);if(y)n=y.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=J(p,T);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.model();if(typeof n=="string"&&n){let p=c.getColumns(),f=p.find(y=>y.columnName===n);if(f)n=f.databaseName;else {let y=c.primaryKey||"id",T=p.find(b=>b.columnName===y);if(T)n=T.databaseName;else {let b=c?.databaseCaseConvention||"preserve";n=J(n||y,b);}}}else {let p=c.primaryKey||"id",y=c.getColumns().find(T=>T.columnName===p);if(y)n=y.databaseName;else {let T=c?.databaseCaseConvention||"preserve";n=J(p,T);}}}let s=this.models.find(c=>c.table===t.table),a=s?.getColumns()||[],l=t.relation.columnName,u=a.find(c=>c.columnName===l);if(u)l=u.databaseName;else {let c=s?.databaseCaseConvention||"preserve";l=J(l,c);}if(t.relation.type==="belongsTo"){let c=a.find(p=>p.columnName===t.relation.foreignKey);if(c)l=c.databaseName;else {let p=s?.databaseCaseConvention||"preserve";l=J(t.relation.foreignKey,p);}}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let c=t.relation.manyToManyOptions.leftForeignKey,p=S(c),f=a.find(y=>y.columnName===p);if(f)l=f.databaseName;else {let y=s?.databaseCaseConvention||"preserve";l=J(p,y);}}let d=t.relation.onDelete?.toLowerCase(),m=t.relation.onUpdate?.toLowerCase();return this.sql.schema().alterTable(t.table,c=>{let p=o||Y(t.table,l,e);c.addConstraint("foreign_key",{columns:[l],references:{table:e,columns:[n]},constraintName:p,onDelete:d,onUpdate:m});}).toQueries()}formatSqlStatements(t){return t.map(e=>({...e,sqlStatements:e.sqlStatements.map(r=>sqlFormatter.format(r,{...this.sql.inputDetails.queryFormatOptions}).replace(/\n/g," ").replace(/\s+/g," "))}))}};zr.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var It=zr;var Gr=class Gr{constructor(t){this.sql=t,this.models=Object.values(this.sql._models);}generateCode(t){let e=[],r=[],o=null,n={STRUCTURE_CREATION:"Structure creation",CONSTRAINT_CREATION:"Constraints and indexes",DESTRUCTIVE_OPERATIONS:"Destructive operations"};for(let s of t){s.phase!==o&&(o=s.phase,e.length>0&&e.push(""),e.push(`// ${n[o]}`));let{up:a,down:l}=this.generateOperationCode(s);a&&e.push(...a),l&&r.push(...l);}return {up:e,down:r}}generateOperationCode(t){switch(t.type){case "CREATE_TABLE":return this.generateCreateTableCode(t);case "ADD_COLUMN":return this.generateAddColumnCode(t);case "MODIFY_COLUMN":return this.generateModifyColumnCode(t);case "DROP_COLUMN":return this.generateDropColumnCode(t);case "CREATE_INDEX":return this.generateCreateIndexCode(t);case "DROP_INDEX":return this.generateDropIndexCode(t);case "ADD_FOREIGN_KEY":return this.generateAddForeignKeyCode(t);case "DROP_FOREIGN_KEY":return this.generateDropForeignKeyCode(t);case "ADD_UNIQUE_CONSTRAINT":return this.generateAddUniqueCode(t);case "DROP_CONSTRAINT":return this.generateDropConstraintCode(t);case "ADD_CHECK_CONSTRAINT":return this.generateAddCheckCode(t);case "ADD_PRIMARY_KEY":return this.generateAddPrimaryKeyCode(t);case "DROP_TABLE":return this.generateDropTableCode(t);case "MODIFY_PRIMARY_KEY":return this.generateModifyPrimaryKeyCode(t);default:return {up:null,down:null}}}generateCreateTableCode(t){let e=t.data,r=[];r.push(`this.schema.createTable(${this.quote(e.table)}, (table) => {`);for(let n of e.columns){let s=this.generateColumnCode(e.table,n,true);r.push(` ${s}`);}r.push("});");let o=[`this.schema.dropTable(${this.quote(e.table)});`];return {up:r,down:o}}generateAddColumnCode(t){let{table:e,column:r}=t.data,o=this.generateColumnCode(e,r,false),n=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.addColumn((col) => ${o.replace(/^table\./,"col.")});`,"});"],s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r.databaseName)});`,"});"];return {up:n,down:s}}generateModifyColumnCode(t){let{table:e,modelColumn:r,dbColumns:o}=t.data,n=this.generateColumnCodeForModify(e,r,o),s=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.alterColumn((col) => ${n.replace(/^table\./,"col.")});`,"});"],a=[`// TODO: reverse column modification for ${this.quote(o.name)} on ${this.quote(e)}`];return {up:s,down:a}}generateDropColumnCode(t){let{table:e,column:r}=t.data,o=[`this.schema.alterTable(${this.quote(e)}, (table) => {`,` table.dropColumn(${this.quote(r)});`,"});"],n=[`// TODO: reverse column drop for ${this.quote(r)} on ${this.quote(e)}`];return {up:o,down:n}}generateCreateIndexCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=(r?.getIndexes().find(u=>u.name===e.index)?.columns||[]).map(u=>r?.getColumns().find(m=>m.columnName===u)?.databaseName||u),s=n.length===1?this.quote(n[0]):`[${n.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.createIndex(${this.quote(e.table)}, ${s}, { constraintName: ${this.quote(e.index)} });`],l=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`];return {up:a,down:l}}generateDropIndexCode(t){let e=t.data,r=[`this.schema.dropIndex(${this.quote(e.index)}, ${this.quote(e.table)});`],o=[`// TODO: reverse index drop for ${this.quote(e.index)} on ${this.quote(e.table)}`];return {up:r,down:o}}generateAddForeignKeyCode(t){let e=t.data,{sourceColumn:r,referencedTable:o,referencedColumn:n,constraintName:s}=this.resolveRelationDetails(e),a=e.relation.onDelete?.toLowerCase(),l=e.relation.onUpdate?.toLowerCase(),u=[];s&&u.push(`constraintName: ${this.quote(s)}`),a&&u.push(`onDelete: ${this.quote(a)}`),l&&u.push(`onUpdate: ${this.quote(l)}`);let d=u.length>0?`, { ${u.join(", ")} }`:"",m=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.foreignKey(${this.quote(r)}, ${this.quote(o)}, ${this.quote(n)}${d});`,"});"],c=s||Y(e.table,r,o),p=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.dropConstraint(${this.quote(c)});`,"});"];return {up:m,down:p}}generateDropForeignKeyCode(t){let e=t.constraint||t.data?.relation?.name;if(!e)return {up:null,down:null};let r=t.table||t.data?.table,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(e)});`,"});"],n=[`// TODO: reverse FK drop for ${this.quote(e)} on ${this.quote(r)}`];return {up:o,down:n}}generateAddUniqueCode(t){let e=t.data,r=this.models.find(u=>u.table===e.table),n=`[${(e.columns||[]).map(u=>r?.getColumns().find(m=>m.columnName===u)?.databaseName||u).map(u=>this.quote(u)).join(", ")}]`,s=e.name||"mandatory",a=[`this.schema.addUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`],l=[`this.schema.dropUnique(${this.quote(e.table)}, ${n}, { constraintName: ${this.quote(s)} });`];return {up:a,down:l}}generateDropConstraintCode(t){let e=t.data,r=t.table||e.table,o=t.constraint||e.name;if(!o||!r)return {up:null,down:null};if(e.type==="primary_key"){let a=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});"],l=[`// TODO: reverse primary key drop on ${this.quote(r)}`];return {up:a,down:l}}if(e.type==="unique"){let a=e.column,l=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],u=[`// TODO: reverse unique constraint drop for ${this.quote(a)} on ${this.quote(r)}`];return {up:l,down:u}}if(e.expression!==void 0){let a=[`this.schema.dropCheck(${this.quote(r)}, ${this.quote(o)});`],l=[`// TODO: reverse check constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:a,down:l}}let n=[`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.dropConstraint(${this.quote(o)});`,"});"],s=[`// TODO: reverse constraint drop for ${this.quote(o)} on ${this.quote(r)}`];return {up:n,down:s}}generateAddCheckCode(t){let e=t.data,r=[`this.schema.addCheck(${this.quote(e.table)}, ${this.quote(e.expression)}, { constraintName: ${this.quote(e.name)} });`],o=[`this.schema.dropCheck(${this.quote(e.table)}, ${this.quote(e.name)});`];return {up:r,down:o}}generateAddPrimaryKeyCode(t){let e=t.data,n=this.models.find(u=>u.table===e.table)?.getColumns().find(u=>u.columnName===e.columns[0])?.primaryKeyConstraintName||fe(e.table,e.columns[0]),s=`[${e.columns.map(u=>this.quote(u)).join(", ")}]`,a=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`,` table.addConstraint("primary_key", { columns: ${s}, constraintName: ${this.quote(n)} });`,"});"],l=[`this.schema.alterTable(${this.quote(e.table)}, (table) => {`," table.dropPrimaryKey();","});"];return {up:a,down:l}}generateDropTableCode(t){let e=t.table||t.data?.table,r=[`this.schema.dropTable(${this.quote(e)});`],o=[`// TODO: reverse table drop for ${this.quote(e)}`];return {up:r,down:o}}generateModifyPrimaryKeyCode(t){let e=t.data,r=e.table,o=[`this.schema.alterTable(${this.quote(r)}, (table) => {`," table.dropPrimaryKey();","});",`this.schema.alterTable(${this.quote(r)}, (table) => {`,` table.addPrimaryKey(${this.quote(e.modelPrimaryKey)});`,"});"],n=[`// TODO: reverse primary key modification on ${this.quote(r)}`];return {up:o,down:n}}generateColumnCode(t,e,r){let o=this.generateColumnTypeCode(e);if(!r)return o;if(e.isPrimary){let n=e.primaryKeyConstraintName||fe(t,e.columnName);o+=`.primaryKey({ constraintName: ${this.quote(n)} })`;}return e.unsigned&&(o+=".unsigned()"),e.zerofill&&(o+=".zerofill()"),e.constraints?.default!==void 0&&(o+=`.default(${this.formatDefaultValue(e.constraints.default)})`),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o+";"}generateColumnCodeForModify(t,e,r){let o=this.generateColumnTypeCode(e);return e.constraints?.default!==void 0?o+=`.default(${this.formatDefaultValue(e.constraints.default)})`:r.defaultValue!=null&&r.defaultValue!==""&&(o+=".default(null)"),e.constraints?.nullable===false?o+=".notNullable()":e.constraints?.nullable===true&&(o+=".nullable()"),o}generateColumnTypeCode(t){let e=t.databaseName;if(Array.isArray(t.type)){let s=t.type.map(a=>this.quote(a)).join(", ");return `table.enum(${this.quote(e)}, [${s}])`}let r=t.type;if(new Set(["uuid","ulid","boolean","year","json","jsonb","binary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]).has(r))return `table.${r}(${this.quote(e)})`;if(r==="timestamp"||r==="datetime"){let s=[];return t.withTimezone&&s.push("withTimezone: true"),t.precision!=null&&s.push(`precision: ${t.precision}`),s.length>0?`table.${r}(${this.quote(e)}, { ${s.join(", ")} })`:`table.${r}(${this.quote(e)})`}return r==="date"||r==="time"?t.precision!=null?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="increment"||r==="bigIncrement"?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:r==="decimal"||r==="numeric"?t.precision!=null?t.scale!=null?`table.${r}(${this.quote(e)}, ${t.precision}, ${t.scale})`:`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="float"||r==="double"||r==="real"?t.precision!=null&&t.precision!==10?`table.${r}(${this.quote(e)}, ${t.precision})`:`table.${r}(${this.quote(e)})`:r==="longtext"||r==="mediumtext"||r==="tinytext"?`table.${r}(${this.quote(e)})`:new Set(["varchar","char","string","integer","tinyint","smallint","mediumint","bigint","biginteger","varbinary"]).has(r)?t.length!=null&&t.length!==255?`table.${r}(${this.quote(e)}, ${t.length})`:`table.${r}(${this.quote(e)})`:Gr.BUILTIN_COLUMN_TYPES.has(r)?`table.${r}(${this.quote(e)})`:t.length!=null?`table.custom(${this.quote(e)}, ${this.quote(r)}, ${t.length})`:`table.custom(${this.quote(e)}, ${this.quote(r)})`}resolveRelationDetails(t){let e=t.table,r="id";if(t.relation.type==="belongsTo"){let l=t.relation.model();e=l.table;let u=l.primaryKey||"id";r=l.getColumns().find(c=>c.columnName===u)?.databaseName||u;}else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){e=S(t.relation.manyToManyOptions.throughModel);let l=S(t.relation.manyToManyOptions.rightForeignKey);l&&l!=="undefined"?r=l:r=t.relation.model().primaryKey||"id";}let n=this.models.find(l=>l.table===t.table)?.getColumns()||[],s=t.relation.columnName;if(t.relation.type==="belongsTo")s=n.find(u=>u.columnName===t.relation.foreignKey)?.databaseName||t.relation.foreignKey;else if(t.relation.type==="manyToMany"&&t.relation.manyToManyOptions){let l=S(t.relation.manyToManyOptions.leftForeignKey);s=n.find(d=>d.columnName===l)?.databaseName||l;}else s=n.find(u=>u.columnName===s)?.databaseName||s;let a=typeof t.relation.constraintName=="string"?t.relation.constraintName:S(t.relation.constraintName)||void 0;return {sourceColumn:s,referencedTable:e,referencedColumn:r,constraintName:a}}quote(t){return `"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}formatDefaultValue(t){return t==null?"null":t==="NULL"?'"NULL"':typeof t=="boolean"||typeof t=="number"?t.toString():t==="TRUE"||t==="true"?"true":t==="FALSE"||t==="false"?"false":this.quote(String(t))}};Gr.BUILTIN_COLUMN_TYPES=new Set(["char","varchar","string","text","longtext","mediumtext","tinytext","uuid","ulid","integer","tinyint","smallint","mediumint","bigint","biginteger","float","double","real","decimal","numeric","increment","bigIncrement","boolean","date","time","datetime","timestamp","year","json","jsonb","binary","varbinary","blob","tinyblob","mediumblob","longblob","geometry","point","linestring","polygon","multiPoint"]);var Yr=Gr;function og(i){return i.replace(/\s+/g," ").trim()}function ng(i){return i.replace(/\s*\([^)]*\)/g,"").trim()}function sg(i){let t=i.split(/\s+/).filter(o=>o.length>0),e=[],r=[];for(let o of t)o==="unsigned"||o==="zerofill"?e.push(o):r.push(o);return {bareBase:r.join(" "),modifiers:e}}function ig(i,t){return t.length===0?i:`${i} ${t.join(" ")}`}function Qe(i,t){let e=og(t.toLowerCase()),r=ng(e);switch(i){case "sqlite":{let o=[{test:n=>n==="increment",normalized:"integer"},{test:n=>n==="bigincrement",normalized:"integer"},{test:n=>n.includes("int"),normalized:"integer"},{test:n=>n==="string",normalized:"varchar"},{test:n=>n.includes("char"),normalized:"varchar"},{test:n=>n.includes("text"),normalized:"text"},{test:n=>n.includes("clob"),normalized:"text"},{test:n=>n.includes("date"),normalized:"text"},{test:n=>n.includes("time"),normalized:"text"},{test:n=>n.includes("timestamp"),normalized:"text"},{test:n=>n.includes("datetime"),normalized:"text"},{test:n=>n.includes("blob"),normalized:"blob"},{test:n=>n.includes("real")||n.includes("floa")||n.includes("doub"),normalized:"real"},{test:n=>n.includes("numeric"),normalized:"numeric"},{test:n=>n.includes("bool"),normalized:"integer"},{test:n=>n.includes("uuid"),normalized:"varchar"},{test:n=>n.includes("ulid"),normalized:"varchar"},{test:n=>n.includes("jsonb"),normalized:"text"},{test:n=>n.includes("json"),normalized:"text"}];for(let n of o)if(n.test(r))return n.normalized;return r}case "mysql":case "mariadb":{let{bareBase:o,modifiers:n}=sg(r),a=new Set(["int","integer","increment","tinyint","smallint","mediumint","bigint","bigincrement","float","double","double precision","real","decimal","numeric","year","bool","boolean"]).has(o);if(o.endsWith("text")||o==="text")return "text";let l;switch(o){case "int":case "integer":case "increment":l="integer";break;case "tinyint":l="boolean";break;case "smallint":l="smallint";break;case "mediumint":l="mediumint";break;case "bigint":case "bigincrement":l="bigint";break;case "float":l="float";break;case "double":case "double precision":l="double";break;case "real":l="double";break;case "decimal":case "numeric":l="numeric";break;case "string":case "varchar":case "character varying":l="varchar";break;case "char":case "character":l="char";break;case "uuid":l="varchar";break;case "ulid":l="varchar";break;case "date":l="date";break;case "datetime":l="datetime";break;case "timestamp":l="timestamp";break;case "time":l="time";break;case "year":l="year";break;case "jsonb":l="json";break;case "json":l="json";break;case "enum":l="enum";break;case "binary":l="binary";break;case "varbinary":l="varbinary";break;case "tinyblob":l="tinyblob";break;case "mediumblob":l="mediumblob";break;case "longblob":l="longblob";break;case "blob":l="blob";break;case "boolean":case "bool":l="boolean";break;default:l=o;break}return a&&n.length>0?ig(l,n):l}case "postgres":case "cockroachdb":{if(r.endsWith("text")||r==="text")return "text";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("time"))return "time";if(r==="datetime")return "timestamp";switch(r){case "string":case "varchar":case "character varying":return "varchar";case "char":case "character":return "char";case "ulid":return "varchar";case "double precision":return "double";case "real":return "real";case "float":return "real";case "integer":case "int4":case "int":case "increment":case "serial":return "integer";case "mediumint":return "integer";case "bigint":case "int8":case "bigincrement":case "bigserial":return "bigint";case "smallint":case "int2":return "smallint";case "tinyint":return "smallint";case "uuid":return "uuid";case "year":return "smallint";case "bytea":return "bytea";case "binary":case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":return "bytea";case "boolean":case "bool":return "boolean";case "numeric":case "decimal":return "numeric";case "jsonb":return "jsonb";case "json":return "json";case "date":return "date";default:return r}}case "mssql":{if(r.endsWith("text")||r==="text"||r==="ntext")return "text";if(r.startsWith("datetime2"))return "datetime2";if(r.startsWith("datetimeoffset"))return "datetimeoffset";switch(r){case "int":case "integer":case "increment":return "int";case "tinyint":return "tinyint";case "smallint":return "smallint";case "bigint":case "bigincrement":return "bigint";case "float":return "float";case "real":return "real";case "double":case "double precision":return "float";case "decimal":case "numeric":return "decimal";case "money":return "money";case "smallmoney":return "smallmoney";case "string":case "varchar":case "character varying":return "varchar";case "nvarchar":return "nvarchar";case "char":case "character":return "char";case "nchar":return "nchar";case "uuid":case "uniqueidentifier":return "uniqueidentifier";case "ulid":return "varchar";case "date":return "date";case "datetime":return "datetime";case "smalldatetime":return "smalldatetime";case "time":return "time";case "timestamp":return "datetime2";case "binary":return "binary";case "varbinary":case "blob":case "tinyblob":case "mediumblob":case "longblob":case "bytea":return "varbinary";case "image":return "image";case "bit":case "boolean":case "bool":return "bit";case "json":case "jsonb":return "nvarchar";case "xml":return "xml";case "sql_variant":return "sql_variant";default:return r}}case "oracledb":{if(r.endsWith("clob")||r==="clob"||r==="nclob")return "clob";if(r.startsWith("timestamp"))return "timestamp";if(r.startsWith("interval"))return "interval";switch(r){case "string":case "varchar":case "varchar2":case "nvarchar2":case "character varying":return "varchar2";case "char":case "nchar":case "character":return "char";case "number":case "numeric":case "decimal":case "integer":case "int":case "smallint":case "tinyint":case "mediumint":case "bigint":return "number";case "binary_float":case "float":case "real":return "binary_float";case "binary_double":case "double":case "double precision":return "binary_double";case "date":return "date";case "blob":case "raw":case "long raw":case "bytea":case "binary":case "varbinary":return "blob";case "json":case "jsonb":return "clob";case "boolean":case "bool":return "number";case "uuid":case "ulid":return "varchar2";default:return r}}default:return r}}var Zr=class i{constructor(t){this.emptyStatements=[/^alter table [`'"]?[\w]+[`'"]?\s*$/i];this.sql=t,this.models=Object.values(this.sql._models),this.data={columnsToAdd:[],columnsToDrop:[],columnsToModify:[],indexesToAdd:[],indexesToDrop:[],uniquesToAdd:[],uniquesToDrop:[],checksToAdd:[],checksToDrop:[],tablesToAdd:[],relationsToAdd:[],relationsToDrop:[],relationsToModify:[],primaryKeysToAdd:[],primaryKeysToDrop:[],primaryKeysToModify:[]};}static async makeDiff(t){let e=new i(t);return await Promise.all(e.models.map(async r=>{let o=await e.sql.getTableSchema(r.table),n={columns:r.getColumns().filter(y=>y?.type!==void 0&&y?.type!==null),indexes:r.getIndexes(),relations:r.getRelations()};if(!o.columns.length){e.data.tablesToAdd.push({table:r.table,columns:n.columns});for(let b of n.indexes)o.indexes.map(C=>C.name).includes(b.name)||e.data.indexesToAdd.push({table:r.table,index:b.name});let y=r.getUniques?.()||[];for(let b of y)e.data.uniquesToAdd.push({table:r.table,name:b.name||"mandatory",columns:b.columns});let T=r.getChecks?.()||[];for(let b of T)e.data.checksToAdd.push({table:r.table,name:b.name,expression:b.expression});for(let b of n.relations){if(b.type!=="belongsTo")continue;let C=S(b.constraintName);o.foreignKeys.find(q=>q.name===C)||e.data.relationsToAdd.push({table:r.table,relation:b,onDelete:b.onDelete,onUpdate:b.onUpdate});}return}for(let y of n.columns)o.columns.some(b=>b.name===y.databaseName||b.name===y.columnName)||e.data.columnsToAdd.push({table:r.table,column:y});let s=r.getColumns();for(let y of o.columns)s.some(b=>b.databaseName===y.name||b.columnName===y.name)||e.data.columnsToDrop.push({table:r.table,column:y.name});for(let y of n.indexes)o.indexes.map(T=>T.name).includes(y.name)||e.data.indexesToAdd.push({table:r.table,index:y.name});let a=r.getUniques?.()||[];for(let y of a)o.indexes.some(b=>b.name===y.name&&b.isUnique)||e.data.uniquesToAdd.push({table:r.table,name:y.name||"mandatory",columns:y.columns});let l=o.foreignKeys.map(y=>y.name);for(let y of o.indexes)y.isUnique||l.includes(y.name)||n.indexes.map(b=>b.name).includes(y.name)||e.data.indexesToDrop.push({table:r.table,index:y.name});for(let y of o.indexes){if(!y.isUnique||y.name==="PRIMARY")continue;(r.getUniques?.()||[]).map(b=>b.name).includes(y.name)||e.data.uniquesToDrop.push({table:r.table,name:y.name});}let u=r.getChecks?.()||[];for(let y of u)o.checkConstraints.some(b=>b.name===y.name)||e.data.checksToAdd.push({table:r.table,name:y.name,expression:y.expression});let d=new Set(u.map(y=>y.name)),m=n.columns.filter(y=>Array.isArray(y.type)),c=new Set(m.map(y=>y.databaseName||y.columnName));for(let y of o.checkConstraints)if(!d.has(y.name)){let T=[...c].find(b=>{let C=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),A=new RegExp(`[\\["\\[]?${C}[\\]"\\]]?\\s*\\)\\s*IN\\s*\\(`,"i"),q=new RegExp(`[\\("\\[]?${C}[\\)"\\]]?(?:::text)?\\s*=\\s*ANY\\s*\\(`,"i");return A.test(y.expression)||q.test(y.expression)});if(T){let b=m.find(A=>(A.databaseName||A.columnName)===T),C=o.columns.find(A=>A.name===T);if(b&&C?.enumValues&&Array.isArray(b.type)){let A=[...b.type].sort(),q=[...C.enumValues].sort();if(!(A.length===q.length&&A.every((D,_)=>D===q[_]))){e.data.checksToDrop.push({table:r.table,name:y.name});let D=e.sql.getDbType(),_=D==="mssql"?"[":'"',v=D==="mssql"?"]":'"',W=b.type.map($=>`'${$.replace(/'/g,"''")}'`).join(", ");e.data.checksToAdd.push({table:r.table,name:y.name,expression:`${_}${T}${v} IN (${W})`});}}}else e.data.checksToDrop.push({table:r.table,name:y.name});}for(let y of n.columns){let T=o.columns.find(A=>A.name===y.databaseName||A.name===y.columnName);if(!T)continue;let b=!e.areColumnsEqual(T,y,o.indexes),C=e.getDefaultChange({table:r.table,dbColumns:T,modelColumn:y});(b||C)&&e.data.columnsToModify.push({table:r.table,dbColumns:T,modelColumn:y});}for(let y of n.relations){if(y.type!=="belongsTo"&&y.type!=="manyToMany")continue;if(y.type==="manyToMany"&&y.manyToManyOptions){let C=S(y.manyToManyOptions.throughModel);e.data.relationsToAdd.push({table:C,relation:{type:"belongsTo",model:()=>r,columnName:S(y.manyToManyOptions.leftForeignKey),foreignKey:y.manyToManyOptions.leftForeignKey,constraintName:y.constraintName?S(y.constraintName):Y(C,S(y.manyToManyOptions.leftForeignKey||$e(r.table)),r.table),onDelete:y.onDelete,onUpdate:y.onUpdate},onDelete:y.onDelete,onUpdate:y.onUpdate});continue}let T=S(y.constraintName);if(T&&o.foreignKeys.some(C=>C.name===T))continue;o.foreignKeys.find(C=>e.relationMatchesDbRelation(r,y,C))||e.data.relationsToAdd.push({table:r.table,relation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}let p=new Set(n.relations.filter(y=>y.type==="belongsTo").map(y=>{let T=S(y.foreignKey)||y.columnName,C=r.getColumns().find(A=>A.columnName===T)?.databaseName||T;return S(y.constraintName)||Y(r.table,C,y.model().table)}));for(let y of o.foreignKeys){if(y.name&&p.has(y.name))continue;n.relations.find(b=>b.type!=="belongsTo"&&b.type!=="manyToMany"?false:e.relationMatchesDbRelation(r,b,y))||e.data.relationsToDrop.push({table:r.table,relation:y});}for(let y of n.relations){if(y.type!=="belongsTo"&&y.type!=="manyToMany")continue;let T=o.foreignKeys.find(b=>e.relationMatchesDbRelation(r,y,b));T&&!e.areRelationsEqual(T,y)&&e.data.relationsToModify.push({table:r.table,dbRelation:T,modelRelation:y,onDelete:y.onDelete,onUpdate:y.onUpdate});}let f=r.primaryKey;if(f&&!o.primaryKey&&e.data.primaryKeysToAdd.push({table:r.table,columns:[f]}),o.primaryKey&&!f&&e.data.primaryKeysToDrop.push({table:r.table,columns:o.primaryKey.columns,name:o.primaryKey.name}),f&&o.primaryKey){let y=r.getColumns().find(T=>T.columnName===f);y&&!e.arePrimaryKeysEqual(o.primaryKey,y)&&e.data.primaryKeysToModify.push({table:r.table,dbPrimaryKey:o.primaryKey,modelPrimaryKey:f});}})),await e.processManyToMany(),await e.removeFkChurnByName(),e}getSqlStatements(){let t=this.getSqlStatementsByPhase();return Object.values(t).flat().filter(r=>{let o=r.trim();return o?!this.emptyStatements.some(n=>n.test(o)):false})}getCodeStatements(){let e=new It(this.sql).generateOperations(this.data);return new Yr(this.sql).generateCode(e)}getSqlStatementsByPhase(){let t=new It(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=Qe(n,t.dataType),a=typeof e.type=="string"?Qe(n,e.type):void 0,l=s.split(" ").filter(d=>d!=="unsigned"&&d!=="zerofill").join(" ");if(a&&o&&(o=l===a),Array.isArray(e.type)&&(n==="mysql"||n==="mariadb")){let d=[...e.type].sort(),m=t.enumValues?[...t.enumValues].sort():null;m&&o&&(o=d.length===m.length&&d.every((c,p)=>c===m[p]));}e.length!=null&&t.length!=null&&o&&(o=t.length===e.length);let u=a==="real"||a==="double"||a==="float";if(e.precision!=null&&t.precision!=null&&((n==="postgres"||n==="cockroachdb")&&u||o&&(o=t.precision===e.precision)),e.scale!=null&&t.scale!=null&&((n==="postgres"||n==="cockroachdb")&&u||o&&(o=t.scale===e.scale)),typeof e.type=="string"&&(a==="timestamp"||a==="time")&&(n==="postgres"||n==="cockroachdb")&&e.withTimezone!==void 0&&t.withTimezone!==void 0&&o&&(o=!!t.withTimezone==!!e.withTimezone),e.constraints?.nullable!==void 0){let d=e.constraints.nullable,m=t.isNullable;o=o&&d===m;}if(n==="mysql"||n==="mariadb"){if(e.unsigned!==void 0){let d=e.unsigned??false,m=t.unsigned??false;o&&(o=d===m);}if(e.zerofill!==void 0){let d=e.zerofill??false,m=t.zerofill??false;o&&(o=d===m);}}if(e.stringMode!==void 0){let d=e.stringMode??false,m=t.stringMode??false;o&&(o=d===m);}return o}areRelationsEqual(t,e){let r=S(e.constraintName),o=r?t.name===r:true;if(e.type==="belongsTo"){let u=e.model(),d=u.primaryKey||"id",m=u.getColumns().find(f=>f.columnName===d),c=u.table,p=m?.databaseName||d;o=o&&t.referencedTable===c&&!!t.referencedColumns&&t.referencedColumns.length===1&&t.referencedColumns[0]===p;}else if(e.type==="manyToMany"&&e.manyToManyOptions){let u=S(e.manyToManyOptions.throughModel);o=o&&t.referencedTable===u;}let n=t.onDelete?.toLowerCase(),s=t.onUpdate?.toLowerCase(),a=e.onDelete?.toLowerCase(),l=e.onUpdate?.toLowerCase();return a&&o&&(o=n===a),l&&o&&(o=s===l),o}relationMatchesDbRelation(t,e,r){let o,n=e;if(n&&n.model){if(typeof n.model=="function"&&n.model.table)o=n.model;else if(typeof n.model=="function")try{let y=n.model();y&&y.table&&(o=y);}catch{}}if(!o)return false;let s=e.type==="belongsTo"?o.table:e.type==="manyToMany"&&e.manyToManyOptions?S(e.manyToManyOptions.throughModel):void 0;if(s&&r.referencedTable!==s)return false;let a=S(e.constraintName);if(a&&r.name&&a!==r.name)return false;let l=t.getColumns(),d=(n.type||"belongsTo")==="belongsTo"?S(n.foreignKey):n.columnName,m=l.find(y=>y.columnName===d);m&&(d=m.databaseName);let c=o.primaryKey||"id",f=o.getColumns().find(y=>y.columnName===c)?.databaseName||c;return r.columns.length===1&&r.columns[0]===d&&r.referencedColumns.length===1&&r.referencedColumns[0]===f}arePrimaryKeysEqual(t,e){if(t.columns.length!==1)return false;let o=t.columns[0]===e.databaseName,n=this.sql.getDbType();if(["mysql","mariadb"].includes(n))return o;let a=!t.name||!e.primaryKeyConstraintName||t.name===e.primaryKeyConstraintName;return o&&a}getDefaultChange(t){let e=this.sql.getDbType(),r=Qe(e,t.dbColumns.dataType),o=typeof t.modelColumn.type=="string"?Qe(e,t.modelColumn.type):void 0;if(o&&r!==o||t.modelColumn.length!=null&&t.dbColumns.length!=null&&t.dbColumns.length!==t.modelColumn.length||t.modelColumn.precision!=null&&t.dbColumns.precision!=null&&t.dbColumns.precision!==t.modelColumn.precision||t.modelColumn.scale!=null&&t.dbColumns.scale!=null&&t.dbColumns.scale!==t.modelColumn.scale||(this.sql.getDbType()==="postgres"||this.sql.getDbType()==="cockroachdb")&&typeof t.modelColumn.type=="string"&&(o==="timestamp"||o==="time")&&t.modelColumn.withTimezone!==void 0&&t.dbColumns.withTimezone!==void 0&&!!t.dbColumns.withTimezone!=!!t.modelColumn.withTimezone)return false;let s=t.modelColumn.constraints?.default!==void 0,a=t.dbColumns.defaultValue!==null&&t.dbColumns.defaultValue!==void 0,l=t.modelColumn.type==="bigIncrement"||t.modelColumn.type==="increment",u=typeof t.dbColumns.defaultValue=="string"&&t.dbColumns.defaultValue.includes("nextval(");if(s&&!a)return "set";if(!s&&a)return l&&u?false:"drop";if(s&&a){let d=String(t.dbColumns.defaultValue),m=String(t.modelColumn.constraints?.default),c=this.normalizeDefaultValue(e,r,d),p=this.normalizeDefaultValue(e,o||r,m);return c!==p?"set":false}return false}normalizeDefaultValue(t,e,r){let o=String(r).trim();if(!o)return o;if(t==="postgres"||t==="cockroachdb"){if(e==="json"||e==="jsonb")try{o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::(jsonb?|[a-zA-Z_ ]+[\[\]]*)/g,"");let s=o.match(/^'(.*)'$/s);if(s&&(o=s[1]),o==="{}"||o==="")return "{}";let a=JSON.parse(o);return JSON.stringify(a)}catch{}o=o.replace(/^\((.*)\)$/s,"$1"),o=o.replace(/::[a-zA-Z_ ]+[\[\]]*/g,"");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),/^true$/i.test(o)?"true":/^false$/i.test(o)?"false":/^null$/i.test(o)?"null":(o)}if(t==="mysql"||t==="mariadb"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);if(n&&(o=n[1]),/^current_timestamp(?:\(\d+\))?$/i.test(o))return "current_timestamp";if(e==="boolean"){if(/^1$/.test(o))return "true";if(/^0$/.test(o))return "false"}return o}if(t==="sqlite"){o=o.replace(/^\((.*)\)$/s,"$1");let n=o.match(/^'(.*)'$/s);return n&&(o=n[1]),o.toLowerCase()}return o}async processManyToMany(){let t=new Set;for(let e of this.models){let r=e.getRelations();for(let o of r){if(o.type!=="manyToMany"||!o.manyToManyOptions||o.manyToManyOptions.wasModelProvided)continue;let n=S(o.manyToManyOptions.throughModel);if(t.has(n))continue;t.add(n);let s=this.models.find($=>$.table===o?.manyToManyOptions?.primaryModel),a=o.model();if(!s||!a)continue;let l=s.primaryKey||"id",u=a.primaryKey||"id",d=s.getColumns().find($=>$.columnName===l),m=a.getColumns().find($=>$.columnName===u);if(!d||!m)continue;let c=S(o.manyToManyOptions.leftForeignKey)||l,p=S(o.manyToManyOptions.rightForeignKey)||u,f=await this.sql.getTableSchema(n);if(!f.columns.length){this.data.tablesToAdd.push({table:n,columns:[this.clonePkAsColumn(d,c),this.clonePkAsColumn(m,p)]}),this.pushM2mFkRelations({throughTable:n,leftModel:s,rightModel:a,leftFkName:c,rightFkName:p,onDelete:o.onDelete,onUpdate:o.onUpdate,constraintName:void 0});continue}let y=this.clonePkAsColumn(d,c),T=this.clonePkAsColumn(m,p),b=f.columns.find($=>$.name===c),C=f.columns.find($=>$.name===p),A=b?this.areColumnsEqual(b,y,f.indexes):false,q=C?this.areColumnsEqual(C,T,f.indexes):false;for(let $ of f.foreignKeys){let V=$.referencedTable===s.table,X=$.referencedTable===a.table;if(!V&&!X)continue;let xe=V?c:p,qe=$.columns[0];qe&&qe!==xe&&(this.data.relationsToDrop.push({table:n,relation:$}),qe!==c&&qe!==p&&this.data.columnsToDrop.push({table:n,column:qe}));}let O={};A||(O[y.databaseName]=y),q||(O[T.databaseName]=O[T.databaseName]||T);for(let $ of Object.keys(O))this.data.columnsToAdd.push({table:n,column:O[$]});let D=this.buildBelongsToRelation(n,()=>s,c,l,void 0,o.onDelete,o.onUpdate),_=this.buildBelongsToRelation(n,o.model,p,u,void 0,o.onDelete,o.onUpdate),v=f.foreignKeys.find($=>$.referencedTable===s.table&&$.columns.length===1&&$.columns[0]===c),W=f.foreignKeys.find($=>$.referencedTable===a.table&&$.columns.length===1&&$.columns[0]===p);if(!v){let $=f.foreignKeys.find(V=>V.referencedTable===s.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(D);}if(!W){let $=f.foreignKeys.find(V=>V.referencedTable===a.table);$&&this.data.relationsToDrop.push({table:n,relation:$}),this.data.relationsToAdd.push(_);}}}}async removeFkChurnByName(){let t=new Set;for(let o of this.data.relationsToAdd)t.add(o.table);for(let o of this.data.relationsToDrop)t.add(o.table);let e=new Map;for(let o of t){let n=await this.sql.getTableSchema(o),s=new Set((n.foreignKeys||[]).map(a=>a.name).filter(Boolean));e.set(o,s);}let r=new Map;for(let o of this.models){let n=o.getRelations(),s=new Set;for(let a of n){if(a.type!=="belongsTo")continue;let l=a.foreignKey||a.columnName,d=o.getColumns().find(c=>c.columnName===l)?.databaseName||l,m=S(a.constraintName)||Y(o.table,d,a.model().table);s.add(m);}r.set(o.table,s);}this.data.relationsToAdd=await Promise.all(this.data.relationsToAdd.map(async o=>{let n=await this.sql.getTableSchema(o.table),s=this.models.find(y=>y.table===o.table),a=s?.getColumns()||[],l=o.relation.columnName;o.relation.type==="belongsTo"?l=a.find(T=>T.columnName===o.relation.foreignKey)?.databaseName||o.relation.foreignKey:l=a.find(T=>T.columnName===l)?.databaseName||l;let u=o.table,d=o.relation.foreignKey;if(o.relation.type==="belongsTo"){let y=o.relation.model();u=y.table;let T=y.primaryKey||"id";d=y.getColumns().find(C=>C.columnName===T)?.databaseName||T;}let m=new Set([l,o.relation.columnName].filter(Boolean)),c=n.foreignKeys.some(y=>{if(y.columns.length!==1||y.referencedColumns.length!==1)return false;let T=m.has(y.columns[0]),b=y.referencedTable===u,C=y.referencedColumns[0]===d;return T&&b&&C}),p=S(o.relation.constraintName)||Y(o.table,l,u),f=e.get(o.table)||new Set;if(c||p&&f.has(p))return null;if(o.relation.type==="manyToMany"&&o.relation.manyToManyOptions){let y=S(o.relation.manyToManyOptions.throughModel),T=S(o.relation.manyToManyOptions.leftForeignKey),b=S(o.relation.manyToManyOptions.rightForeignKey),C=o.table===y&&o.relation.columnName===T&&o.relation.model().table===s?.table,A=o.table===y&&o.relation.columnName===b&&o.relation.model().table!==s?.table,q=await this.sql.getTableSchema(y),O=q.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===T&&_.referencedTable===(s?.table||"")),D=q.foreignKeys.some(_=>_.columns.length===1&&_.columns[0]===b&&_.referencedTable===o.relation.model().table);if(C&&O||A&&D)return null}return o})).then(o=>o.filter(Boolean)),this.data.relationsToDrop=await Promise.all(this.data.relationsToDrop.map(async o=>{let n=this.models.find(u=>u.table===o.table);if(!n)return o;let s=n.getRelations(),a=n.getColumns();return s.some(u=>{if(u.type!=="belongsTo")return false;let m=a.find(T=>T.columnName===u.foreignKey)?.databaseName||u.foreignKey,c=u.model(),p=c.primaryKey||"id",y=c.getColumns().find(T=>T.columnName===p)?.databaseName||p;return o.relation.columns.length===1&&o.relation.columns[0]===m&&o.relation.referencedTable===c.table&&o.relation.referencedColumns.length===1&&o.relation.referencedColumns[0]===y})?null:o})).then(o=>o.filter(Boolean));}clonePkAsColumn(t,e){let r=t.type;return r==="bigIncrement"?r="bigint":r==="increment"&&(r="integer"),{columnName:e,databaseName:e,isPrimary:false,type:r,length:t.length,precision:t.precision,scale:t.scale,withTimezone:t.withTimezone,constraints:{nullable:false}}}pushM2mFkRelations(t){let e=this.buildBelongsToRelation(t.throughTable,()=>t.leftModel,t.leftFkName,t.leftModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate),r=this.buildBelongsToRelation(t.throughTable,()=>t.rightModel,t.rightFkName,t.rightModel.primaryKey||"id",t.constraintName,t.onDelete,t.onUpdate);this.data.relationsToAdd.push(e),this.data.relationsToAdd.push(r);}buildBelongsToRelation(t,e,r,o,n,s,a){let l=n?S(n):Y(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 My=(i,t)=>({table:i,modelCaseConvention:"preserve",databaseCaseConvention:t?.databaseCaseConvention??"preserve",softDeleteColumn:t?.softDeleteColumn??"deleted_at",softDeleteValue:t?.softDeleteValue??He()});var ag=async i=>(await ce.getDriver(i)).client,Xr=async(i,t)=>{let e=await ag(i);switch(i){case "mariadb":case "mysql":let r=t;return e.createPool({host:r.host,port:r.port,user:r.username,password:r.password,database:r.database,...r?.driverOptions});case "postgres":case "cockroachdb":let s=t,a=e;return new a.Pool({host:s.host,port:s.port,user:s.username,password:s.password,database:s.database,...s?.driverOptions});case "sqlite":let u=e,d=t,m=d?.database;return new u.Database(m,d?.driverOptions?.mode??void 0,D=>{if(D)throw new g("SqliteDataSource::createSqlPool","CONNECTION_NOT_ESTABLISHED")});case "mssql":let p=e,f=t,{options:y,...T}=f.driverOptions??{},b=new p.ConnectionPool({server:f.host??"localhost",port:f.port,database:f.database,user:f.username,password:f.password,...T,options:{trustServerCertificate:E.MSSQL_TRUST_SERVER_CERTIFICATE??void 0,...y,abortTransactionOnError:false,enableImplicitTransactions:false}});return await b.connect(),b;case "oracledb":let C=e,A=t,q=`${A.host}/${A.database}`;return await C.createPool({user:A.username,password:A.password,connectString:q,...A.driverOptions});default:throw new g("SqlConnectionUtils::createSqlPool",`UNSUPPORTED_DATABASE_TYPE_${i}`)}};var Et=class Et{constructor(){}static run(t,e){return Et.storage.run(t,e)}static getTransaction(){return Et.storage.getStore()}};Et.storage=new async_hooks.AsyncLocalStorage;var Ke=Et;var Pt=class i{constructor(t,e,r=false,o=0){this.connectionReleased=false;this.sql=t,this.isActive=false,this.transactionId=Re__default.default.randomBytes(16).toString("hex"),this.isolationLevel=e,this.isNested=r,this.nestingDepth=o;}async nestedTransaction(t){let e=new i(this.sql,this.isolationLevel,true,this.nestingDepth+1);if(await e.transaction(),t)try{let r=await Ke.run(e,()=>t(e));return await e.commit(),r}catch(r){throw await e.rollback(),r}return e}async transaction(){let t=this.getIsolationLevelQuery();if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`SAVE TRANSACTION ${e}`),this.isActive=true;return;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return;case "sqlite":await this.sql.rawQuery(`SAVEPOINT ${e}`),this.isActive=true;return}}switch(this.sql.type){case "mssql":t&&await this.sql.rawQuery(t),te("BEGIN TRANSACTION",this.sql.logs);let e=await this.getMssqlTransactionLevel();await this.sql.sqlConnection.begin(e),this.isActive=true;break;case "mysql":case "mariadb":t&&await this.sql.rawQuery(t);let r=this.sql.sqlConnection;te("BEGIN TRANSACTION",this.sql.logs),await r.beginTransaction(),this.isActive=true;break;case "postgres":case "cockroachdb":await this.sql.rawQuery("BEGIN TRANSACTION"),t&&await this.sql.rawQuery(t),this.isActive=true;break;case "sqlite":t&&await this.sql.rawQuery(t),await this.sql.rawQuery("BEGIN TRANSACTION"),this.isActive=true;break;case "oracledb":t&&await this.sql.rawQuery(t),this.isActive=true;break}}async commit(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new g("TRANSACTION::commit","TRANSACTION_NOT_ACTIVE");R.warn("Transaction::commit - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":case "oracledb":break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "sqlite":await this.sql.rawQuery(`RELEASE SAVEPOINT ${e}`);break}this.isActive=false;return}try{switch(this.sql.type){case "mssql":te("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;te("COMMIT",this.sql.logs),await e.commit();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("COMMIT");break;case "sqlite":await this.sql.rawQuery("COMMIT");break;case "oracledb":te("COMMIT",this.sql.logs),await this.sql.sqlConnection.commit();break}}catch(e){throw R.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async rollback(t){if(!this.isActive){if(t?.throwErrorOnInactiveTransaction)throw new g("TRANSACTION::rollback","TRANSACTION_NOT_ACTIVE");R.warn("Transaction::rollback - TRANSACTION_NOT_ACTIVE");return}if(this.isNested){let e=this.getSavePointName();switch(this.sql.type){case "mssql":await this.sql.rawQuery(`ROLLBACK TRANSACTION ${e}`);break;case "mysql":case "mariadb":case "postgres":case "cockroachdb":case "oracledb":await this.sql.rawQuery(`ROLLBACK TO SAVEPOINT ${e}`);break;case "sqlite":await this.sql.rawQuery(`ROLLBACK TO ${e}`);break;default:throw new g("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}this.isActive=false;return}try{switch(this.sql.type){case "mssql":te("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;case "mysql":case "mariadb":let e=this.sql.sqlConnection;te("ROLLBACK",this.sql.logs),await e.rollback();break;case "postgres":case "cockroachdb":await this.sql.rawQuery("ROLLBACK");break;case "sqlite":await this.sql.rawQuery("ROLLBACK");break;case "oracledb":te("ROLLBACK",this.sql.logs),await this.sql.sqlConnection.rollback();break;default:throw new g("TRANSACTION::rollback",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){throw R.error(e),e}finally{await this.releaseConnection(),this.isActive=false;}}async releaseConnection(){if(this.connectionReleased)return;let t=null;try{switch(this.sql.type){case "mssql":break;case "mysql":case "mariadb":this.sql.sqlConnection.release();break;case "postgres":case "cockroachdb":this.sql.sqlConnection.release();break;case "sqlite":break;case "oracledb":await this.sql.sqlConnection.close();break;default:throw new g("TRANSACTION::releaseConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}}catch(e){t=e,R.error(e);}try{await this.sql.disconnect();}catch(e){R.warn(`Transaction::releaseConnection - disconnect failed: ${e?.message??e}`);}if(this.sql.sqlConnection=null,this.connectionReleased=true,t)throw t}getIsolationLevelQuery(){if(!this.isolationLevel||this.sql.type==="mssql")return "";if(this.sql.type==="sqlite"&&this.isolationLevel!=="SERIALIZABLE")throw new g("TRANSACTION::getIsolationLevelQuery","SQLITE_ONLY_SUPPORTS_SERIALIZABLE_ISOLATION_LEVEL");if(this.sql.type==="mysql"||this.sql.type==="mariadb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="postgres"||this.sql.type==="cockroachdb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="oracledb")return `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel}`;if(this.sql.type==="sqlite")return "";throw new g("TRANSACTION::getIsolationLevelQuery",`UNSUPPORTED_DATABASE_TYPE_${this.sql.type}`)}getSavePointName(){let t=this.transactionId.slice(0,8).toUpperCase();return `sp_${this.nestingDepth}_${t}`}async getMssqlTransactionLevel(){if(!this.isolationLevel)return;let t=await import('mssql').then(e=>e.default.ISOLATION_LEVEL).catch(e=>{throw R.error(e),new k("mssql")});switch(this.isolationLevel){case "READ UNCOMMITTED":return t.READ_UNCOMMITTED;case "READ COMMITTED":return t.READ_COMMITTED;case "REPEATABLE READ":return t.REPEATABLE_READ;case "SERIALIZABLE":return t.SERIALIZABLE;default:throw new g("TRANSACTION::getMssqlTransactionLevel",`UNSUPPORTED_ISOLATION_LEVEL_${this.isolationLevel}`)}}};var Hl=Symbol.for("hysteria.orm.SqlDataSource"),Oy,xy,Oe=class i extends(xy=dt,Oy=Hl,xy){constructor(e){super(e);this[Oy]=true;this.globalTransaction=null;this.globalTransactionLock=null;this.ownsPool=false;this.roundRobinIndex=0;this.sqlConnection=null;this.id=Re.randomUUID();this.logicalSourceId=Re.randomUUID();this.cacheAdapter=new Nr;this.migrationConfig={path:E.MIGRATION_PATH||"database/migrations",lock:true,transactional:true,lockTimeout:3e4};this.seederConfig={path:"database/seeders"};this.zodEngine=null;this.lazyLoad=false;this.connecting=null;this.sqlType=e?.type||this.type;let r=e;this.inputDetails={...e,type:this.sqlType,host:r?.host??this.host,port:r?.port??this.port,username:r?.username??this.username,password:r?.password??this.password,database:r?.database??this.database,logs:r?.logs??this.logs},this.inputDetails.connectionPolicies=e?.connectionPolicies||{retry:{maxRetries:0,delay:0}},this.inputDetails.queryFormatOptions=e?.queryFormatOptions||{language:gt(this.sqlType),keywordCase:"lower",dataTypeCase:"lower",functionCase:"lower"},this.cacheKeys=e?.cacheStrategy?.keys??{},this.cacheAdapter=e?.cacheStrategy?.cacheAdapter??this.cacheAdapter,this.adminJsOptions=e?.adminJs,e?.migrations&&(this.migrationConfig={path:e.migrations.path||this.migrationConfig.path,tsconfig:e.migrations.tsconfig,lock:e.migrations.lock??this.migrationConfig.lock,transactional:"transactional"in e.migrations?e.migrations.transactional??this.migrationConfig.transactional:this.migrationConfig.transactional}),e?.seeders&&(this.seederConfig={path:e.seeders.path||this.seederConfig.path,tsconfig:e.seeders.tsconfig}),this._models=e?.models||{},this.slaves=(e?.replication?.slaves||[]).map(o=>new i(o)),this.slaveAlgorithm=e?.replication?.slaveAlgorithm||"roundRobin",this.onSlaveServerFailure=e?.replication?.onSlaveServerFailure,this.lazyLoad=e?.lazyLoad??false,this.clsEnabled=e?.clsEnabled??true;}static isSqlDataSource(e){return typeof e=="object"&&e!==null&&Hl in e&&e[Hl]===true}get isClsEnabled(){return this.clsEnabled}getOnSlaveServerFailure(){return this.onSlaveServerFailure}addObserver(e){return this.observerChain||(this.observerChain=new ot([])),this.observerChain.add(e),this}static async useConnection(e,r){let o=new i(e);await o.connect();try{await r(o),o.isConnected&&await o.disconnect();}catch(n){throw o.isConnected&&await o.disconnect(),n}}async connect(){if(this.isConnected)throw new g("SqlDataSource::connect","CONNECTION_ALREADY_ESTABLISHED");try{this.sqlPool=await Xr(this.sqlType,this.inputDetails),this.ownsPool=!0,this.slaves.length&&await Promise.all(this.slaves.map(async e=>{e.sqlPool=await Xr(e.sqlType,e.inputDetails),e.ownsPool=!0;}));}catch(e){this.sqlPool=null,this.ownsPool=false;for(let r of this.slaves)r.ownsPool&&(r.sqlPool=null,r.ownsPool=false);throw e}}get isConnected(){return !!this.sqlPool||!!this.sqlConnection}async ensureConnected(){if(!this.isConnected){if(!this.lazyLoad)throw new g("SqlDataSource::ensureConnected","CONNECTION_NOT_ESTABLISHED");this.connecting||(this.connecting=this.connect().finally(()=>{this.connecting=null;})),await this.connecting;}}get isInGlobalTransaction(){return !!this.globalTransaction}get models(){let e=this;return new Proxy(this._models,{get(r,o){if(typeof o=="string"&&o in r)return e.from(r[o])}})}getSlave(){if(!this.slaves.length)return null;if(this.slaveAlgorithm==="random")return this.slaves[Math.floor(Math.random()*this.slaves.length)];let e=this.slaves[this.roundRobinIndex%this.slaves.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%this.slaves.length,e}getTransactionBoundSqlDataSource(){if(this.globalTransaction?.isActive)return this.globalTransaction.sql;if(this.clsEnabled){let e=Ke.getTransaction();if(e?.isActive&&e.sql.logicalSourceId===this.logicalSourceId)return e.sql}return null}async useCache(e,r,...o){if(!this.cacheAdapter)throw new g("SqlDataSource::useCache","CACHE_ADAPTER_NOT_CONFIGURED");let n=this.cacheKeys[e];if(!n)throw new g("SqlDataSource::useCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);let s=n.length,a=typeof r=="number"&&s===o.length,l,u=[];a?(l=r,u=o):(l=void 0,u=r!==void 0?[r,...o]:o);let d=Vl(JSON.stringify(u)),m=d?`${e}:${d}`:e,c=await this.cacheAdapter.get(m);if(c!==void 0)return c;let p=await n(...u);return await this.cacheAdapter.set(m,p,l),p}async invalidCache(e,...r){if(!this.cacheAdapter)throw new g("SqlDataSource::invalidCache","CACHE_ADAPTER_NOT_CONFIGURED");let o=this.cacheKeys[e];if(!o)throw new g("SqlDataSource::invalidCache",`KEY_${e}_HAS_NO_HANDLER_IN_CACHE_KEYS_CONFIG`);if(o.length>0&&r.length===0){let l=e;await this.cacheAdapter.invalidate(l);return}let s=Vl(JSON.stringify(r)),a=s?`${e}:${s}`:e;await this.cacheAdapter.invalidate(a);}async invalidateAllCache(e){if(!this.cacheAdapter)throw new g("SqlDataSource::invalidateAllCache","CACHE_ADAPTER_NOT_CONFIGURED");await this.cacheAdapter.invalidateAll(e);}async clone(e){let r=new i(this.inputDetails);return r.id=this.id,r.logicalSourceId=this.logicalSourceId,r.sqlType==="sqlite"||!!e?.shouldRecreatePool?(r.sqlPool=await Xr(r.sqlType,this.inputDetails),r.ownsPool=true):(r.sqlPool=this.sqlPool,r.ownsPool=false),r}getDbType(){return this.sqlType}from(e,r){let o=this.getTransactionBoundSqlDataSource()??this;if(typeof e=="string"){let n=new Q(My(e,r),o);return r?.alias&&n.table(e,r.alias),n}return new Ie(e,o)}schema(){if(!this.isConnected&&!this.lazyLoad)throw new g("SqlDataSource::schema","CONNECTION_NOT_ESTABLISHED");return new Dt(this,this.getDbType())}async startGlobalTransaction(e){for(;this.globalTransactionLock;)await this.globalTransactionLock;if(this.globalTransaction?.isActive)throw new g("SqlDataSource::startGlobalTransaction","GLOBAL_TRANSACTION_ALREADY_STARTED");let r=()=>{};this.globalTransactionLock=new Promise(o=>{r=o;});try{let o=await this.clone();return o.sqlConnection=await o.getConnection(),this.globalTransaction=new Pt(o,e?.isolationLevel),await this.globalTransaction.transaction(),this.globalTransaction}finally{r(),this.globalTransactionLock=null;}}async commitGlobalTransaction(e){if(!this.globalTransaction)throw new g("SqlDataSource::commitGlobalTransaction","GLOBAL_TRANSACTION_NOT_STARTED");try{await this.globalTransaction.commit({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async rollbackGlobalTransaction(e){if(!this.globalTransaction){R.warn("SqlDataSource::rollbackGlobalTransaction - GLOBAL_TRANSACTION_NOT_STARTED");return}try{await this.globalTransaction.rollback({throwErrorOnInactiveTransaction:e?.throwErrorOnInactiveTransaction});}finally{this.globalTransaction=null;}}async transaction(e,r){let o=typeof e=="function"?r:e;if(this.globalTransaction?.isActive)return typeof e=="function"?this.globalTransaction.nestedTransaction(e):this.globalTransaction.nestedTransaction();let n=this.clsEnabled?Ke.getTransaction():void 0;if(n?.isActive&&n.sql.logicalSourceId===this.logicalSourceId)return typeof e=="function"?n.nestedTransaction(e):n.nestedTransaction();let s=await this.clone();s.sqlConnection=await s.getConnection();let a=new Pt(s,o?.isolationLevel);if(await a.transaction(),typeof e=="function")try{let l=this.clsEnabled?await Ke.run(a,()=>e(a)):await e(a);return await a.commit({throwErrorOnInactiveTransaction:!1}),l}catch(l){throw await a.rollback({throwErrorOnInactiveTransaction:false}),l}return a}getModelManager(e){if(!this.isConnected&&!this.lazyLoad)throw new g("SqlDataSource::getModelManager","CONNECTION_NOT_ESTABLISHED");let r=this.getTransactionBoundSqlDataSource()??this;return new Le(e,r)}getPool(){if(!this.sqlPool)throw this.lazyLoad?new g("SqlDataSource::getPool - call ensureConnected() or connect() first when using lazyLoad","CONNECTION_NOT_ESTABLISHED"):new g("SqlDataSource::getPool","CONNECTION_NOT_ESTABLISHED");return this.sqlPool}async getConnection(){if(this.sqlConnection)return this.sqlConnection;switch(await this.ensureConnected(),this.sqlType){case "mysql":case "mariadb":return await this.sqlPool.getConnection();case "postgres":case "cockroachdb":return await this.sqlPool.connect();case "sqlite":return this.sqlPool;case "mssql":return this.sqlPool.transaction();case "oracledb":return await this.sqlPool.getConnection();default:throw new g("SqlDataSource::getConnection",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}}async disconnect(){if(!this.isConnected){te("Connection already closed or not established",this.logs);return}if(!this.ownsPool){if(this.sqlConnection)try{switch(this.sqlType){case "mysql":case "mariadb":this.sqlConnection.release?.();break;case "postgres":case "cockroachdb":this.sqlConnection.release?.();break;case "oracledb":await this.sqlConnection.close?.();break}}catch(e){R.warn(`SqlDataSource::disconnect - releasing borrowed connection failed: ${e?.message??e}`);}this.sqlConnection=null;return}try{this.globalTransaction?.isActive&&await this.rollbackGlobalTransaction({throwErrorOnInactiveTransaction:!1});}catch{R.warn("SqlDataSource::disconnect - Error while rolling back global transaction");}switch(await this.cacheAdapter?.disconnect?.(),this.slaves.length&&await Promise.all(this.slaves.map(async e=>{try{await e.disconnect();}catch(r){R.warn(`SqlDataSource::disconnect - Error while closing slave connection: ${r.message}`);}})),te("Closing connection",this.logs),this.sqlType){case "mysql":case "mariadb":await this.sqlPool.end();break;case "postgres":case "cockroachdb":await this.sqlPool.end();break;case "sqlite":await new Promise((e,r)=>{this.sqlPool.close(o=>{o&&r(o),e();});});break;case "mssql":await this.sqlPool.close();break;case "oracledb":await this.sqlPool.close();break;default:throw new g("SqlDataSource::disconnect",`UNSUPPORTED_DATABASE_TYPE_${this.sqlType}`)}this.sqlPool=null,this.sqlConnection=null;}getConnectionDetails(){return {type:this.getDbType(),host:this.host,port:this.port,username:this.username,password:this.password,database:this.database,connectionPolicies:this.inputDetails.connectionPolicies,queryFormatOptions:this.inputDetails.queryFormatOptions}}async introspectSchema(){let e=this.getDbType(),r;e==="postgres"||e==="cockroachdb"?r=`