bun-query-builder 0.3.8 → 0.3.10

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.
@@ -1,3 +0,0 @@
1
- // @bun
2
- import{We}from"./chunk-93ny6tvm.js";import{n,e,k,_,b,Fe,m,D,l,at,X}from"./chunk-bpwg9p8b.js";function N(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function De(t){if(typeof t!=="string")return;switch(t.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function Pe(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import{Database as Te}from"bun:sqlite";function te(t){if(typeof t==="number")return{length:t};return t}function me(t){if(typeof t==="number")return{max:t};return t}function Le(t){return typeof t==="function"}function Ue(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function ke(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function z(t,r={}){if(!t)return r;return new Proxy(t,{get(o,s){if(s in r)return r[s];let i=o[s];if(i!==void 0)return i;let a=o[Ue(s)];if(Le(a))return a.bind(o);return}})}function Pt(t){let r=(f)=>{let g=Array.isArray(f)?f:[],R=Math.floor(Math.random()*g.length);return g[R]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=z(t.string,{alpha:(f)=>o()?.alpha?.(te(f)),alphanumeric:(f)=>o()?.alphanumeric?.(te(f)),numeric:(f)=>o()?.numeric?.(te(f)),sample:(f)=>o()?.sample?.(te(f)),hexadecimal:(f)=>o()?.hexadecimal?.(te(f))}),d=z(t.number,{int:(f)=>s()?.int?.(me(f)),float:(f)=>{let g=me(f);return ke(Number(s()?.float?.(g)??0),g)}}),u=z(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let R=[...Array.isArray(f)?f:[]],M=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*R.length));for(let x=R.length-1;x>0;x-=1){let A=Math.floor(Math.random()*(x+1));[R[x],R[A]]=[R[A],R[x]]}return R.slice(0,Math.min(M,R.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let R=g.length-1;R>0;R-=1){let M=Math.floor(Math.random()*(R+1));[g[R],g[M]]=[g[M],g[R]]}return g},maybe:(f,g)=>{let R=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<R?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),T={string:a,number:d,helpers:u,datatype:{boolean:(f)=>{let g=typeof f==="number"?f:f?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(i()?.boolean?.())},number:(f)=>Number(s()?.int?.(me(f))??0),float:(f)=>ke(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(te(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:z(t.address),address:z(t.address),vehicle:z(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:z(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in T)return T[g];let R=f[g];if(R&&typeof R==="object")return z(R);return R}})}function Be(t){if(typeof t==="string")return{model:t};if(t&&typeof t==="object"&&typeof t.model==="string"){let r=t;return{model:r.model,foreignKey:r.foreignKey,onDelete:r.onDelete}}return null}function O(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Be).filter((o)=>o!==null)}function Y(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var $e=/^[A-Z_][A-Z0-9_]*$/i;function H(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);if(t.length>64)throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' exceeds 64 chars`);if(!$e.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Se(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);let o=t.split(".");if(o.length>2||o.some((s)=>s.length===0||s.length>64||!$e.test(s)))throw TypeError(`[bun-query-builder] ${r}: invalid ORDER BY column '${t}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Me(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&X(t)===0)return[];return r}var ae=null,we=new Map;function qe(t,r){we.set(t,r),re.clear()}function Bt(){we.clear(),re.clear()}function j(t){if(!ae)try{ae=import.meta.require("./chunk-82w0fmx3.js").getModel}catch{ae=()=>{return}}return ae(t)??we.get(t)}var le=new Map,He=500;function Ke(t){let r=le.get(t);if(r!==void 0)return r;let o=at(t,"postgres");if(le.size>=He)le.clear();return le.set(t,o),o}function _t(t){if(t==null)return 0;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;if(Array.isArray(t))return t.length;return 0}function It(t){if(t==null||typeof t!=="object")return null;if("insertId"in t&&t.insertId!=null)return t.insertId;if("lastInsertRowid"in t&&t.lastInsertRowid!=null)return t.lastInsertRowid;return null}class pe{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...r))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...r)??void 0)}run(t,r){let o=this.sqliteDb.run(t,r);return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class be{dialect;constructor(t){this.dialect=t}conn(){return b()}text(t){return this.dialect==="postgres"?Ke(t):t}async all(t,r){let o=await this.conn().unsafe(this.text(t),r);return Array.isArray(o)?o:[]}async get(t,r){let o=await this.conn().unsafe(this.text(t),r);if(Array.isArray(o))return o[0]??void 0;return o??void 0}async run(t,r){let o=await this.conn().unsafe(this.text(t),r);return{changes:_t(o),lastInsertId:It(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Ke(t)} RETURNING ${o}`,r),d=Array.isArray(a)?a[0]:a;return{changes:1,lastInsertId:d?d[o]??null:null}}let s=await this.conn().unsafe(t,r),i=It(s);if(i==null&&this.dialect!=="sqlite"){let a=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);i=(Array.isArray(a)?a[0]:a)?.id??null}return{changes:_t(s)||1,lastInsertId:i}}}var Q=null,ce=!1,U=null,ne=null,ue=null,de=null;function Ln(t){if(t.database instanceof Te)Q=t.database,ce=!1;else Q=new Te(t.database||":memory:",{create:!0}),ce=!0,k(Q);U=null,ne=null}function Kn(){let t=ce,r=Q;if(Q=null,ce=!1,U=null,ne=null,ue=null,de=null,t&&r)try{r.close()}catch{}}var Re=!1;function S(){if(Q){if(!U||ne!==Q)U=new pe(Q),ne=Q,ue="sqlite",de=null;return U}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${_()?.url??""}`;if(U&&ne===null&&ue===t&&de===o)return U;if(ne=null,ue=t,de=o,t==="sqlite"&&_())U=new be(t);else if(t==="sqlite"){if(!r&&!Re)Re=!0,console.warn("[bun-query-builder] The model layer has no database configured, so it is using an in-memory SQLite database and nothing it writes will persist. Configure one with setConfig({ dialect, database }) or configureOrm({ database }), or name ':memory:' explicitly to silence this.");let s=new Te(r||":memory:",{create:!0});k(s),U=new pe(s)}else U=new be(t);return U}function Fn(){let t=S();if(t.sqliteDb)return t.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${t.dialect}'. Use the async model API instead.`)}var Qe=4096,_e=1000;function Ve(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[C(a),d]));for(let a of r){let d=String(i.get(a)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let a of o)for(let d of r){let u=a[d];if(u===null||u===void 0||u instanceof Date)continue;let c=typeof u;if(c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="bigint")return!1}return!0}function ze(t,r){return typeof r==="bigint"?r.toString():r}function xe(t){return 2**Math.floor(Math.log2(t))}var L="deleted_at",Ae=500,ye="__btm_rel__";function ee(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Z(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ee=new WeakMap;function Ge(t){let r=Ee.get(t);if(r)return r;let o=new Set,s=t.belongsToMany;if(s){if(Array.isArray(s)){for(let i of s)if(typeof i==="string")o.add(i.toLowerCase());else if(i&&typeof i==="object"&&i.model)o.add(i.model.toLowerCase())}else if(typeof s==="object")for(let i of Object.keys(s))o.add(i)}return Ee.set(t,o),o}function Oe(t){let r={};for(let[o,s]of Object.entries(t))r[C(o)]=s;return r}function Xe(t){for(let r in t)if(C(r)!==r)return Oe(t);return t}function Ye(t,r){if(t[r])return t[r];let o=C(r);if(t[o])return t[o];for(let s of Object.keys(t))if(C(s)===o)return t[s];return}class I{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Xe({...r}),this._original=null;let s=Ge(t);if(s.size===0)return;let i=this;return new Proxy(this,{get(a,d,u){if(typeof d==="string"&&s.has(d)&&!(d in a))return()=>{let c=Ie(t,d);if(!c||c.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let T=j(c.relatedModelName),f=T?.getDefinition?.()||T?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Lt(i,t,c,f)};return Reflect.get(a,d,u)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(t){let r=this._definition.get?.[t];if(r)try{let o=r(this._attributes);if(o!==void 0)return o}catch{}return this._attributes[C(t)]}getAttribute(t){return this._attributes[C(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[C(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[C(o)];return r}except(t){let r=new Set(t.map((s)=>C(s))),o={};for(let s of Object.keys(this._attributes))if(!r.has(s))o[s]=this._attributes[s];return o}getRelation(t){return this._relations[t]}setRelation(t,r){this._relations[t]=r}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let t=this._definition.primaryKey||"id";return this._attributes[t]}isDirty(t){if(this._original===null)return!1;if(t){let r=C(t);return this._attributes[r]!==this._original[r]}return Object.keys(this._attributes).some((r)=>this._attributes[r]!==this._original[r])}isClean(t){return!this.isDirty(t)}getOriginal(t){return this.getOriginalAttributes()[C(t)]}getChanges(){if(this._original===null)return{};let t={};for(let r of Object.keys(this._attributes))if(this._attributes[r]!==this._original[r])t[r]=this._attributes[r];return t}fill(t){let r=this._definition.attributes;for(let[o,s]of Object.entries(t)){let i=Ye(r,o),a=!i&&C(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[C(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Oe(t);Object.assign(this._attributes,r);for(let o of Object.keys(r))this._forced.add(o);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,o=this._definition.attributes,s={};for(let[u,c]of Object.entries(o)){if(c.guarded&&!this._forced.has(C(u)))continue;let T=C(u);if(this._attributes[T]!==void 0)s[T]=this._attributes[T]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in s))s[u]=this._attributes[u];let i=this._attributes[t],d=o[t]?.guarded&&!this._forced.has(t);if(i!=null&&!(t in s)&&!d)s[t]=i;if(Z(this._definition)){let u=Y(),c=this._attributes.created_at;s.created_at=c===void 0||c===null?u:c,s.updated_at=u}if(this._definition.traits?.useUuid&&!s.uuid)s.uuid=crypto.randomUUID();return await r?.beforeCreate?.(s),s}async _markInserted(t,r){let o=this._definition.primaryKey||"id";for(let[s,i]of Object.entries(t))this._attributes[s]=i;if(!(o in t)&&r!=null)this._attributes[o]=r;this._exists=!0,await this._definition.hooks?.afterCreate?.(this),this._original={...this._attributes},this._hasSaved=!0}_applySetters(){let t=this._definition.set||{};for(let[r,o]of Object.entries(t))if(this.isDirty(r))this._attributes[C(r)]=o(this._attributes)}async save(){let t=S(),r=this._definition.primaryKey||"id",o=this._definition.hooks;if(this._exists){this._applySetters(),await o?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let a=i.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(s),this._attributes[r]];if(Z(this._definition)){let u=Y();await t.run(`UPDATE ${this._definition.table} SET ${a}, updated_at = ? WHERE ${r} = ?`,[...Object.values(s),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${a} WHERE ${r} = ?`,d)}await o?.afterUpdate?.(this)}else{let s=await this._prepareInsert(),i=Object.keys(s),a=i.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${i.join(", ")}) VALUES (${a})`,Object.values(s),r);return await this._markInserted(s,r in s?void 0:d.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(o==null)return null;let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return new I(this._definition,s,!0)}async delete(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r],s=this._definition.hooks;if(o==null)throw Error("Cannot delete a model without a primary key");if(await s?.beforeDelete?.(this),ee(this._definition)){let i=Y();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[L]=i}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[o]);return await s?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],o=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await o?.beforeDelete?.(this),await S().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ee(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let t=this._definition.primaryKey||"id",r=this._attributes[t];if(!r)throw Error("Cannot restore a model without a primary key");return await S().run(`UPDATE ${this._definition.table} SET ${L} = ? WHERE ${t} = ?`,[null,r]),this._attributes[L]=null,this._original=null,this}trashed(){return this._attributes[L]!=null}async refresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(!o)throw Error("Cannot refresh a model without a primary key");let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return this._attributes=s,this._original=null,this}replicate(){let t=this._definition.primaryKey||"id",r={...this._attributes};return delete r[t],delete r.uuid,delete r.created_at,delete r.updated_at,new I(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,o]of Object.entries(this._relations))if(Array.isArray(o))t[r]=o.map((s)=>s.toArray());else if(o)t[r]=o.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[o,s]of Object.entries(this._definition.attributes))if(s.hidden)t.add(o);let r={};for(let[o,s]of Object.entries(this._attributes))if(!t.has(o))r[o]=s;for(let[o,s]of Object.entries(this._relations))if(Array.isArray(s))r[o]=s.map((i)=>i.toJSON());else if(s)r[o]=s.toJSON();else r[o]=null;return r}}var ve=new Map,Ne=new Map,re=new Map,Je=1000;function W(t){return C(t)}function C(t){let r=ve.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ve.set(t,r),r}function G(t){let r=Ne.get(t);if(r!==void 0)return r;return r=Fe(t),Ne.set(t,r),r}var fe=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ze=[...fe,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ce(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>typeof s==="string"?s:String(s?.model??"")).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function et(t,r){let o=t.name??t.table??"model",i=Ze.filter((d)=>Ce(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!fe.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${fe.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=fe.flatMap((d)=>Ce(t,d));return a.length>0?`[orm] '${o}' has no relation '${r}'. Available: ${a.join(", ")}.`:`[orm] '${o}' has no relation '${r}' \u2014 it declares no relations at all.`}function Ie(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(w){if(!w)return null;if(Array.isArray(w)){for(let h of w){let K=typeof h==="string"?h:h?.model||"";if(K&&K.toLowerCase()===r.toLowerCase())return K}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||h}return null}function d(){let w=t.belongsTo;if(!w)return null;let h=r.toLowerCase(),K=(p)=>{if(typeof p==="string")return{model:p};if(p&&typeof p==="object"&&typeof p.model==="string")return{model:p.model,foreignKey:p.foreignKey};return null};if(Array.isArray(w)){for(let p of w){let y=K(p);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof w==="object"){for(let[p,y]of Object.entries(w))if(p===r||p.toLowerCase()===h)return K(y)}return null}function u(){let w=t.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let h of w)if(typeof h==="string"){if(h.toLowerCase()===r.toLowerCase())return{entry:h}}else if(h&&typeof h==="object"&&h.model){if(h.model.toLowerCase()===r.toLowerCase())return{entry:h}}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:K}}return null}function c(w){let h=t[w];if(!h)return null;let K=r.toLowerCase();if(Array.isArray(h)){for(let p of h){let y=typeof p==="string"?p:String(p?.model??"");if(!y||y.toLowerCase()!==K)continue;let v=typeof p==="object"?p?.morphName:void 0;return{model:y,morphName:String(v??`${C(o)}able`)}}return null}if(typeof h==="object")for(let[p,y]of Object.entries(h)){let v=typeof y==="string"?y:String(y?.model??"");if(p.toLowerCase()!==K&&v.toLowerCase()!==K)continue;let P=typeof y==="object"?y?.morphName:void 0;return{model:v,morphName:String(P??p)}}return null}for(let w of["morphMany","morphOne"]){let h=c(w);if(!h)continue;let p=j(h.model)?.getTable?.()||G(h.model);return{type:w,relatedModelName:h.model,relatedTable:p,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let T=a(t.hasMany);if(T){let h=j(T)?.getTable?.()||G(T),K=C(o)+"_id";return{type:"hasMany",relatedModelName:T,relatedTable:h,foreignKey:K,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||G(f),K=C(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:K,localKey:i}}let g=d();if(g){let w=g.model,h=j(w),K=h?.getTable?.()||G(w),p=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${C(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:K,foreignKey:y,localKey:p}}let R=u();if(R){let w=typeof R.entry==="object",h=w?R.entry.model:R.entry,p=j(h)?.getTable?.()||G(h),y=w?R.entry:null,v,P;if(y?.table)v=y.table;else if(y?.through){P=y.through;let B=j(y.through);if(!B)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${y.through}'. Make sure '${y.through}' is registered.`);v=B.getTable?.()||B.getDefinition?.()?.table||G(y.through)}else{let B=ie(s),q=ie(p);v=[B,q].sort().join("_")}let F=y?.foreignKey||`${ie(s)}_id`,J=y?.relatedKey||`${ie(p)}_id`,V=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))V.push(B);if(P){let B=j(P),q=B?.getDefinition?.()||B?.definition,he=q?.attributes??{},je=q?.primaryKey??"id";for(let se of Object.keys(he)){if(se===F||se===J||se===je)continue;if(!V.includes(se))V.push(se)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:p,foreignKey:F,localKey:i,pivotTable:v,pivotFkParent:F,pivotFkRelated:J,pivotColumns:V,pivotModelName:P,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let M=(w,h)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let K=w[r]??w[Object.keys(w).find((q)=>q.toLowerCase()===r.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:p,target:y}=K;if(!p||!y)return null;let v=j(p),P=v?.getDefinition?.()||v?.definition,F=v?.getTable?.()||P?.table||G(p),J=P?.primaryKey||"id",B=j(y)?.getTable?.()||G(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${C(o)}_id`,localKey:i,throughTable:F,throughForeignKey:`${C(o)}_id`,throughLocalKey:J,targetForeignKey:`${ie(F)}_id`}},x=M(t.hasManyThrough,"hasManyThrough");if(x)return x;let A=M(t.hasOneThrough,"hasOneThrough");if(A)return A;return null}function ge(t,r){let o=new Set;for(let s of t){let i=s.get(r);if(i!=null)o.add(i)}return[...o]}function ie(t){return m(e.relations?.singularizeStrategy)(t)}class Lt{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,o,s){this._parent=t,this._parentDef=r,this._resolved=o,this._relatedDef=s}get parentId(){let t=this._parentDef.primaryKey||"id";return this._parent.get(t)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(t,r,o){if(o===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivot(t,r,o){if(o===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${o})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${o})`,params:[...r]}),this}wherePivotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NULL`,params:[]}),this}wherePivotNotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NOT NULL`,params:[]}),this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push(`${t} ${r.toUpperCase()}`),this}limit(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${t}`);return this._limit=t,this}offset(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${t}`);return this._offset=t,this}relatedSelectColumns(){let t=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),r=this._relatedDef.traits;if(r?.useTimestamps||r?.timestampable)t.add("created_at"),t.add("updated_at");if(r?.useSoftDeletes||r?.softDeletable)t.add("deleted_at");if(r?.useUuid)t.add("uuid");return[...t]}buildSelect(){let t=[],o=`SELECT ${this.relatedSelectColumns().map((s)=>`${this.relatedTable}.${s} AS ${ye}${s}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;o+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,o+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let s of this._pivotWheres)o+=` AND ${s.sql}`,t.push(...s.params);for(let s of this._wheres)o+=` AND ${s.sql}`,t.push(...s.params);if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}hydrateRows(t){let r=this.fkParent,o=this.fkRelated;return t.map((s)=>{let i={},a={};for(let[u,c]of Object.entries(s))if(u.startsWith(ye))i[u.slice(ye.length)]=c;else if(u!==r&&u!==o)a[u]=c;let d=new I(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=S(),{sql:r,params:o}=this.buildSelect(),s=await t.all(r,o);return this.hydrateRows(s)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=S(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,o=[this.parentId];for(let i of this._pivotWheres)r+=` AND ${i.sql}`,o.push(...i.params);let s=await t.get(r,o);return Number(s?.count??0)}async exists(){return await this.count()>0}now(){return Y()}async attach(t,r={}){let o=S(),s=Array.isArray(t)?t:[t];if(s.length===0)return 0;let i=this._resolved.pivotTimestamps?this.now():null,a=0;for(let d of s){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(i){if(u.created_at===void 0)u.created_at=i;if(u.updated_at===void 0)u.updated_at=i}let c=Object.keys(u),T=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${T})`,g=c.map((R)=>u[R]);await o.run(f,g),a++}return a}async detach(t){let r=S(),o=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];if(t!==void 0&&t!==null){let i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=i.map(()=>"?").join(", ");o+=` AND ${this.fkRelated} IN (${a})`,s.push(...i)}return(await r.run(o,s)).changes}async updateExistingPivot(t,r){let o=S(),s={...r};if(this._resolved.pivotTimestamps&&s.updated_at===void 0)s.updated_at=this.now();let i=Object.keys(s);if(i.length===0)return 0;let a=i.map((c)=>`${c} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((c)=>s[c]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=S(),o=new Map;for(let T of t)if(T!=null&&typeof T==="object"&&"id"in T){let{id:f,...g}=T;o.set(f,g)}else o.set(T,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((T)=>T[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((T)=>!o.has(T));if(c.length>0)await this.detach(c),d.push(...c);for(let[T,f]of o)if(!i.has(T))await this.attach(T,f),a.push(T);else if(Object.keys(f).length>0)await this.updateExistingPivot(T,f),u.push(T);return{attached:a,detached:d,updated:u}}async toggle(t){let r=S(),o=Array.isArray(t)?t:[t];if(o.length===0)return{attached:[],detached:[]};let s=o.map(()=>"?").join(", "),i=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${s})`,[this.parentId,...o]),a=new Set(i.map((c)=>c[this.fkRelated])),d=o.filter((c)=>!a.has(c)),u=o.filter((c)=>a.has(c));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class E{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(t){this._definition=t}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:o,boolean:"and"});return this}orWhere(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:o,boolean:"or"});return this}whereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"and"}),this}orWhereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"or"}),this}whereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"and"}),this}orWhereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"or"}),this}whereNull(t){return H(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return H(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return H(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return H(t,"orWhereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"or"}),this}whereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"and"}),this}orWhereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"or"}),this}whereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"and"}),this}orWhereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"or"}),this}whereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let o=new E(this._definition);if(r(o),o._wheres.length===0)return this;let s=[],i=o.buildWhereClauses(s);if(!i)return this;return this._wheres.push({raw:`(${i})`,rawParams:s,boolean:t}),this}whereBetween(t,r){return H(t,"whereBetween(column)"),this._wheres.push({column:t,operator:">=",value:r[0],boolean:"and"}),this._wheres.push({column:t,operator:"<=",value:r[1],boolean:"and"}),this}whereNotBetween(t,r){H(t,"whereNotBetween(column)");let o=W(t);return this._wheres.push({raw:`(${o} < ? OR ${o} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push({column:t,direction:r}),this}orderByDesc(t){return this.orderBy(t,"desc")}orderByAsc(t){return this.orderBy(t,"asc")}latest(t="created_at"){return this.orderBy(t,"desc")}oldest(t="created_at"){return this.orderBy(t,"asc")}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}select(...t){return this._select=t,this}with(...t){for(let r of t)if(!this._withRelations.includes(r))this._withRelations.push(r);return this}getWithRelations(){return this._withRelations}buildWhereClauses(t){let r=[];for(let o of this._wheres){let s;if(o.raw){if(s=o.raw,o.rawParams&&o.rawParams.length>0)t.push(...o.rawParams)}else if(o.value===null){let i=W(o.column);s=o.operator==="="?`${i} IS NULL`:`${i} IS NOT NULL`}else if(o.operator==="in"||o.operator==="not in"){let i=o.value;s=l(W(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${W(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return D(r)}softDeleteClause(){if(this._trashed==="include"||!ee(this._definition))return"";return this._trashed==="only"?`${L} IS NOT NULL`:`${L} IS NULL`}assertNoUnappliedClauses(t){let r=[];if(this._limit!==void 0)r.push("limit()");if(this._offset!==void 0)r.push("offset()");if(this._orderBy.length>0)r.push("orderBy()");if(r.length>0)throw TypeError(`[orm] ${t}() cannot apply ${r.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(t){let r=this._wheres.length>0?this.buildWhereClauses(t):"",o=this.softDeleteClause();if(r&&o)return`(${r}) AND ${o}`;return r||o}buildQuery(){let t=[],o=`SELECT ${this._select.map((i)=>i==="*"?i:W(i)).join(", ")} FROM ${this._definition.table}`,s=this.composeWhere(t);if(s)o+=` WHERE ${s}`;if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.map((i)=>`${W(i.column)} ${i.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}toSql(){return this.buildQuery()}async eagerLoadRelations(t){if(t.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((r)=>this.eagerLoadRelation(r,t)))}async eagerLoadRelation(t,r){let o=S(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=re.get(i);if(a===void 0){if(a=Ie(this._definition,t),re.size>=Je)re.clear();re.set(i,a)}if(!a)throw Error(et(this._definition,t));let d=a.type==="hasOne"||a.type==="morphOne";if(a.type==="hasMany"||a.type==="hasOne"||a.type==="morphMany"||a.type==="morphOne"){let u=ge(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),T=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${T}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,[]);M.get(A).push(x)}for(let x of r){let A=M.get(x.get(s))||[];x.setRelation(t,A.map((w)=>new I(R,w,!0)))}}else{let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,x)}for(let x of r){let A=M.get(x.get(s));x.setRelation(t,A?new I(R,A,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let x of r){let A=x._attributes[a.foreignKey];if(A!=null)u.add(A)}let c=[...u];if(c.length===0)return;let T=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${T})`,c),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition,M=new Map;for(let x of f)M.set(x[a.localKey],x);for(let x of r){let A=x._attributes[a.foreignKey],w=M.get(A);x.setRelation(t,w?new I(R,w,!0):null)}}if(a.type==="belongsToMany"){let u=ge(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),T=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(T.length===0){for(let p of r)p.setRelation(t,[]);return}let f=new Set;for(let p of T){let y=p[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],R=j(a.relatedModelName),M=R?.getDefinition?.()||R?.definition||this._definition,x=M?.primaryKey||"id",A=[];if(g.length>0){let p=g.map(()=>"?").join(", ");A=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${x} IN (${p})`,g)}let w=new Map;for(let p of A)w.set(p[x],p);let h=new Map;for(let p of T){let y=p[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(p)}let K=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let p of r){let y=p.get(s),P=(h.get(y)||[]).map((F)=>{let J=w.get(F[a.pivotFkRelated]);if(!J)return null;let V=new I(M,J,!0),B={};for(let[q,he]of Object.entries(F))if(!K.has(q))B[q]=he;return V.pivot=B,V}).filter((F)=>F!==null);p.setRelation(t,P)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=ge(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",T=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${T})`,u);if(f.length===0){for(let K of r)K.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let K of f)g.set(K[c],K[a.throughForeignKey]);let R=[...new Set(f.map((K)=>K[c]))],M=R.map(()=>"?").join(", "),x=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${M})`,R),A=j(a.relatedModelName),w=A?.getDefinition?.()||A?.definition||this._definition,h=new Map;for(let K of x){let p=g.get(K[a.targetForeignKey]);if(p==null)continue;if(!h.has(p))h.set(p,[]);h.get(p).push(new I(w,K,!0))}for(let K of r){let p=h.get(K.get(s))||[];K.setRelation(t,a.type==="hasManyThrough"?p:p[0]??null)}}}async get(){let t=S(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new I(this._definition,a,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(i);return i}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let t=await this.first();if(!t)throw Error(`No ${this._definition.name} found`);return t}async find(t){let r=this._definition.primaryKey||"id";return this.where(r,t).first()}async findOrFail(t){let r=await this.find(t);if(!r)throw Error(`${this._definition.name} with id ${t} not found`);return r}async last(){let t=this._definition.primaryKey||"id";return this._orderBy=[{column:t,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let t=S(),r=[],o=`SELECT COUNT(*) as count FROM ${this._definition.table}`,s=this.composeWhere(r);if(s)o+=` WHERE ${s}`;let i=await t.get(o,r);return Number(i?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let t=await this.get();if(t.length===0)throw Error(`No ${this._definition.name} found`);if(t.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return t[0]}async increment(t,r=1){H(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=S(),s=[r],i=W(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(Y());let d=this.composeWhere(s);if(d)a+=` WHERE ${d}`;return(await o.run(a,s)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let o=0;while(!0){let s=new E(this._definition);s._wheres=[...this._wheres],s._orderBy=[...this._orderBy],s._select=[...this._select],s._withRelations=[...this._withRelations],s._trashed=this._trashed,s._limit=t,s._offset=o*t;let i=await s.get();if(i.length===0)break;if(await r(i)===!1)break;if(i.length<t)break;o++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let a=t;r=a.perPage??15,t=a.page??1}let o=await this.count(),s=Math.ceil(o/r);this._limit=r,this._offset=(t-1)*r;let i=await this.get();return{data:i,total:o,page:t,perPage:r,lastPage:s,hasMorePages:t<s,isEmpty:i.length===0,from:i.length>0?(t-1)*r+1:null,to:i.length>0?(t-1)*r+i.length:null,meta:{perPage:r,page:t,total:o,lastPage:s}}}async pluck(t){H(t,"pluck(column)");let r=S(),o=[],s=W(t),i=`SELECT ${s} FROM ${this._definition.table}`,a=this.composeWhere(o);if(a)i+=` WHERE ${a}`;if(this._orderBy.length>0)i+=` ORDER BY ${this._orderBy.map((u)=>`${W(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)i+=` LIMIT ${this._limit}`;if(this._offset!==void 0)i+=` OFFSET ${this._offset}`;return(await r.all(i,o)).map((u)=>u[s])}async aggregate(t,r){H(r,`${t}(column)`);let o=S(),s=[],i=`SELECT ${t}(${W(r)}) as v FROM ${this._definition.table}`,a=this.composeWhere(s);if(a)i+=` WHERE ${a}`;let u=(await o.get(i,s))?.v;if(u==null)return null;if(typeof u==="string"){let c=Number(u);return u.trim()!==""&&!Number.isNaN(c)?c:u}return u}max(t){return this.aggregate("MAX",t)}min(t){return this.aggregate("MIN",t)}async avg(t){return Number(await this.aggregate("AVG",t)??0)||0}async sum(t){return Number(await this.aggregate("SUM",t)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let t=ee(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=S(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${L} IS NULL`:`${L} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Y():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${L} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let c=this._definition.primaryKey||"id",f=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((M)=>new I(this._definition,M,!0)),g=f.map((M)=>M._attributes[c]);if(g.some((M)=>M==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let M of f)await s.beforeDelete?.(M);let R=0;for(let M=0;M<g.length;M+=Ae){let x=g.slice(M,M+Ae),A=`${c} IN (${x.map(()=>"?").join(", ")})`;R+=t?(await r.run(`UPDATE ${o} SET ${L} = ? WHERE ${A}`,[u,...x])).changes:(await r.run(`DELETE FROM ${o} WHERE ${A}`,x)).changes}for(let M of f){if(t)M._attributes[L]=u;await s.afterDelete?.(M)}return R}async update(t){this.assertNoUnappliedClauses("update");let r=S(),o=Object.entries(t),s=o.map(([u])=>`${W(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(Y());let a=`UPDATE ${this._definition.table} SET ${s}${Z(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function tt(t){let r={query:()=>new E(t),where(o,s,i){return new E(t).where(o,s,i)},orWhere(o,s,i){return new E(t).orWhere(o,s,i)},whereIn(o,s){return new E(t).whereIn(o,s)},whereNotIn(o,s){return new E(t).whereNotIn(o,s)},whereNull(o){return new E(t).whereNull(o)},whereNotNull(o){return new E(t).whereNotNull(o)},whereLike(o,s){return new E(t).whereLike(o,s)},orderBy(o,s="asc"){return new E(t).orderBy(o,s)},orderByDesc(o){return new E(t).orderByDesc(o)},select(...o){return new E(t).select(...o)},with(...o){return new E(t).with(...o)},limit:(o)=>new E(t).limit(o),take:(o)=>new E(t).take(o),skip:(o)=>new E(t).skip(o),withTrashed:()=>new E(t).withTrashed(),onlyTrashed:()=>new E(t).onlyTrashed(),async find(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new I(t,d,!0):void 0},async findOrFail(o){let s=await r.find(o);if(!s)throw Error(`${t.name} with id ${o} not found`);return s},async findMany(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new I(t,u,!0))},all:()=>new E(t).get(),first:()=>new E(t).first(),firstOrFail:()=>new E(t).firstOrFail(),last:()=>new E(t).last(),count:()=>new E(t).count(),exists:()=>new E(t).exists(),doesntExist:()=>new E(t).doesntExist(),paginate:(o,s)=>new E(t).paginate(o,s),whereBetween(o,s){return new E(t).whereBetween(o,s)},whereNotBetween(o,s){return new E(t).whereNotBetween(o,s)},async create(o){let s=new I(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((c)=>new I(t,c,!1));if(!s.length)return[];let i=S(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,T)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(T);else u.set(f,[T])});for(let[c,T]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let M of T){let x=d[M],A=Object.keys(x),w=await i.insert(A.length?`INSERT INTO ${t.table} (${A.join(", ")}) VALUES (${A.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(x),a);await s[M]._markInserted(x,g?w.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&Ve(t,f,T.map((M)=>d[M]))){let M=t.table,x=f.join(", "),A=`INSERT INTO ${M} (${x}) SELECT ${x} FROM jsonb_populate_recordset(NULL::${M}, (?::text)::jsonb)`;for(let w=0;w<T.length;w+=_e){let h=T.slice(w,w+_e),K=JSON.stringify(h.map((v)=>Object.fromEntries(f.map((P)=>[P,d[v][P]??null]))),ze);if(!g){await i.run(A,[K]);for(let v of h)await s[v]._markInserted(d[v]);continue}let p=(await i.all(`${A} RETURNING ${a}`,[K])).map((v)=>v[a]),y=p.every((v)=>typeof v==="number"||typeof v==="bigint")?[...p].sort((v,P)=>v<P?-1:v>P?1:0):p;for(let v=0;v<h.length;v++)await s[h[v]]._markInserted(d[h[v]],y[v])}continue}let R=xe(Math.max(1,Math.floor(Qe/f.length)));for(let M=0;M<T.length;){let x=Math.min(R,xe(T.length-M)),A=T.slice(M,M+x);M+=x;let w=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${A.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=A.flatMap((y)=>f.map((v)=>d[y][v]));if(!g){await i.run(w,h);for(let y of A)await s[y]._markInserted(d[y]);continue}let K=(await i.all(`${w} RETURNING ${a}`,h)).map((y)=>y[a]),p=K.every((y)=>typeof y==="number"||typeof y==="bigint")?[...K].sort((y,v)=>y<v?-1:y>v?1:0):K;for(let y=0;y<A.length;y++)await s[A[y]]._markInserted(d[A[y]],p[y])}}return s},async updateOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);let a=await i.first();if(a)return await a.update(s),a;return this.create({...o,...s})},async firstOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);return await i.first()||this.create({...o,...s})},async update(o,s){let i=await r.findOrFail(o);return await i.update(s),i},async delete(o){let s=await r.find(o);return s?s.delete():!1},destroy(o){return r.delete(o)},async forceDelete(o){let s=await r.withTrashed().find(o);return s?s.forceDelete():!1},remove(o){return r.forceDelete(o)},async truncate(){await S().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new E(t).orderByDesc(o),oldest:(o="created_at")=>new E(t).orderBy(o,"asc"),max:(o)=>new E(t).max(o),min:(o)=>new E(t).min(o),avg:(o)=>new E(t).avg(o),sum:(o)=>new E(t).sum(o),pluck(o){return new E(t).pluck(o)}};return new Proxy(r,{get(o,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let i=s.slice(5),a=i.charAt(0).toLowerCase()+i.slice(1);if(a in t.attributes||a==="id"||a===t.primaryKey)return(d)=>new E(t).where(a,d)}return Reflect.get(o,s)}})}function Kt(t){let r=tt(t);if(t?.name)qe(t.name,r);return r}async function jn(t){let r=S(),o=C(t.primaryKey||"id"),s=[],i=new Set([o]);if(s.push(t.autoIncrement!==!1?`${o} INTEGER PRIMARY KEY AUTOINCREMENT`:`${o} INTEGER PRIMARY KEY`),t.traits?.useUuid)s.push("uuid TEXT UNIQUE"),i.add("uuid");for(let[a,d]of Object.entries(t.attributes)){let u=C(a);if(i.has(u))continue;i.add(u);let c=De(d.type),T=Pe(c);if(u.endsWith("_id")&&(c===void 0||N(c)))T="INTEGER";let f=`${u} ${T}`;if(d.unique)f+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let g=d.foreignKey;if(f+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)f+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)f+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}s.push(f)}for(let a of O(t.belongsTo)){let d=a.foreignKey??`${C(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(Z(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(ee(t)&&!i.has("deleted_at"))i.add("deleted_at"),s.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${s.join(", ")})`,[])}async function qn(t,r,o){let s=S(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=Pt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<a;d++){let u={};for(let[T,f]of Object.entries(t.attributes))if(f.factory)u[C(T)]=f.factory(o);if(Z(t)){let T=Y();u.created_at=T,u.updated_at=T}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let c=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${c.join(", ")}) VALUES (${c.map(()=>"?").join(", ")})`,Object.values(u))}}var oe=new Map;function rn(t){return oe.get(t)}function sn(){return[...oe.values()]}function an(){return Object.fromEntries(oe)}function on(t){return oe.has(t)}function ln(){oe.clear(),Bt()}function Ft(t,r){return oe.set(t,r),r}function nt(){return typeof window<"u"&&typeof document<"u"}function cn(t){let r;if(nt())r=We(t);else{let o=Kt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return Ft(t.name,r),r}function un(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
3
- export{N,Pe,Pt,Be,O,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un};
@@ -1,3 +0,0 @@
1
- // @bun
2
- import{n,e,t,s,_e,b,r,m,Ht,D,l,X,je,qe}from"./chunk-bpwg9p8b.js";import{Buffer as St}from"buffer";import{serialize as Mt}from"v8";function vt(p){return m(e.relations?.singularizeStrategy)(p)}function E(p,B,w,j={}){let re=j.singularize??vt,oe=p.relations?.[B]?.belongsToMany?.[w];if(oe==null)return null;let Ee=typeof oe==="object",pe=Ee?oe:null,be=Ee?pe.model:oe,He=p.modelToTable[be]||be,Ve,et;if(pe?.table)Ve=pe.table;else if(pe?.through){if(et=pe.through,Ve=p.modelToTable[pe.through],!Ve)throw Error(`[query-builder] belongsToMany relation '${w}' on '${B}' references unknown through model '${pe.through}'. Make sure '${pe.through}' is registered via defineModels({...}).`)}else{let Je=re(B),h=re(He);Ve=[Je,h].sort().join("_")}let tt=pe?.foreignKey??`${re(B)}_id`,ct=pe?.relatedKey??`${re(He)}_id`,ne={};if(pe?.pivot?.columns)Object.assign(ne,pe.pivot.columns);if(et&&j.models){let Je=j.models[et],h=Je?.definition??Je?.getDefinition?.()??Je,g=h?.attributes??{};for(let[d,y]of Object.entries(g)){if(d===tt||d===ct||d===(h?.primaryKey??"id"))continue;ne[d]={default:y?.default,nullable:y?.nullable,validation:y?.validation}}}let Qe=Boolean(pe?.pivot?.timestamps),xe=Object.keys(ne);return{pivotTable:Ve,fkParent:tt,fkRelated:ct,pivotColumns:xe,pivotColumnDefs:ne,pivotModelName:et,timestamps:Qe,relatedModelName:be,relatedTable:He,hasConfig:Ee}}function*In(p,B={}){let w=p.relations;if(!w)return;for(let[j,re]of Object.entries(w)){let N=re?.belongsToMany;if(!N)continue;for(let oe of Object.keys(N)){let Ee=E(p,j,oe,B);if(Ee)yield{parentTable:j,relationKey:oe,resolved:Ee}}}}function Fe(p){return typeof p==="object"&&p!==null&&"raw"in p&&typeof p.raw==="string"}function pt(p,B,w){if(Array.isArray(B)){let re=s(B.length,w.length+1),N=l(p,B,!1,re);return w.push(...B),N}let j=`${p} = ${t(w.length+1)}`;return w.push(B),j}function Ge(p){return typeof p==="object"&&p!==null&&"sql"in p&&typeof p.sql==="string"&&(!("parameters"in p)||Array.isArray(p.parameters))}function Wt(p,B){let[w,...j]=B;if(j.length>0||w!==void 0&&!Array.isArray(w))throw TypeError("[query-builder] db.raw(sql, bindings): pass the bindings as one array, db.raw('a = ? AND b = ?', [a, b]).");let re={sql:p,parameters:[...w??[]]};return Object.defineProperty(re,"then",{enumerable:!1,value:(N,oe)=>{let Ee=TypeError("[query-builder] db.raw(sql, bindings) builds a fragment for set() or where(), not a query. Run SQL with db.unsafe(sql, params).");if(typeof oe==="function")return oe(Ee);throw Ee}}),re}function it(p){return p instanceof Promise&&typeof p.execute==="function"&&typeof p.cancel==="function"}function lt(p){throw TypeError(`[query-builder] ${p}: a Bun \`sql\`...\`\` query cannot be used as a fragment, because its SQL text is not readable. Bind values with db.raw('name = ?', [value]) or { sql, parameters }, or use the exported \`raw\` tagged template.`)}function Ye(p,B){let w=p.parameters??(Array.isArray(p.values)?p.values:[]);if(e.dialect!=="postgres"||w.length===0)return{text:p.sql,parameters:w};let j=0,{text:re}=je(p.sql,()=>j<w.length?t(B+j++):void 0);if(j!==w.length)throw TypeError(`[query-builder] SQL expression declares ${w.length} parameters but contains only ${j} placeholders`);return{text:re,parameters:w}}function kt(p,B){if(B.length===2){let[w,j]=B;if(Array.isArray(j)&&typeof w==="number"&&j[w]===p)return!1;if(j instanceof Set&&w===p&&j.has(p))return!1;if(j instanceof Map&&j.get(w)===p)return!1}return B.some((w)=>w!==void 0&&!(Array.isArray(w)&&w.length===0))}function en(p,...B){if(typeof p==="string"){if(!(B.length===1&&Number.isInteger(B[0])&&B[0]>=0&&!p.includes("?"))&&kt(p,B))throw TypeError("[query-builder] raw(string) takes no values, so the argument(s) after the string would be dropped. Use raw as a tagged template instead, which interpolates each value as an escaped literal.");return{raw:p}}let w=p[0];for(let j=0;j<B.length;j++)w+=Ke(B[j])+p[j+1];return{raw:w}}function De(p){return n(e.dialect)?`\`${p.replace(/`/g,"``")}\``:`"${p.replace(/"/g,'""')}"`}function ft(p,B=1){let w=Object.keys(p[0]??{}),j=[],re=B,N=p.map((oe)=>`(${w.map((pe)=>(j.push(oe[pe]),t(re++))).join(", ")})`);return{colsSql:w.map(De).join(", "),valuesSql:N.join(", "),params:j,nextIndex:re}}function ut(p){return Boolean(p&&(p.onSlowQuery||p.slowQueryThresholdMs!=null&&p.slowQueryThresholdMs>=0))}function c(p,B=e.dialect){if(!n(B))return p;let w=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(p.trim());if(!w)return p;let[,j,re,N]=w,oe=re?`\`${j}\`.\`${re}\``:`\`${j}\``;return N?`${oe} AS \`${N}\``:oe}function Ct(p,B=e.dialect){if(!n(B)||p===null||p===void 0)return p;if(typeof p==="string"){let w=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(p);if(!w)return p;let[,j,re]=w;return`${j} ${re.length===5?`${re}:00`:re}`}if(!(p instanceof Date)||Number.isNaN(p.getTime()))return p;return p.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function $t(p){if(typeof p==="string")return c(p);if(Fe(p))return p.raw;if(p&&typeof p==="object"){let B=p;if(typeof B.raw==="function")return String(B.raw());if(typeof B.sql==="string")return B.sql;let w=String(p);if(w!=="[object Object]")return w}throw TypeError(`[query-builder] select(): unsupported column ${String(p)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function Ft(p){let B=/\(|\)|\bORDER\s+BY\b/gi,w=0,j;while(j=B.exec(p))if(j[0]==="(")w++;else if(j[0]===")")w=Math.max(0,w-1);else if(w===0)return!0;return!1}var ye={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},Bt=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function F(p,B){if(!ye.IDENTIFIER.test(p)){let w=B?` in ${B}`:"";throw Error(`[query-builder] Invalid identifier${w}: '${p}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function $e(p,B){if(typeof p!=="string")throw TypeError(`[query-builder] ${B}: operator must be a string, got ${typeof p}`);let w=p.toLowerCase();if(!Bt.has(w))throw TypeError(`[query-builder] ${B}: refusing to use '${p}' as a SQL operator \u2014 not in the allowed set (${[...Bt].join(", ")})`);return p}function Ue(p,B,w,j){let re=B.toLowerCase();if(re!=="is"&&re!=="is not")return null;if(w!==null&&w!==void 0)throw TypeError(`[query-builder] ${j}: operator '${B}' only accepts NULL/undefined as value, got ${typeof w} (${String(w)})`);return`${p} IS ${re==="is not"?"NOT ":""}NULL`}function Pe(p,B){if(typeof p!=="string"||p.length===0)throw TypeError(`[query-builder] ${B}: identifier must be a non-empty string, got ${typeof p}`);if(p.length>129)throw TypeError(`[query-builder] ${B}: identifier '${p}' too long`);let w=p.split(".");if(w.length>2)throw TypeError(`[query-builder] ${B}: identifier '${p}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let j of w)if(!/^[A-Z_][A-Z0-9_]*$/i.test(j))throw TypeError(`[query-builder] ${B}: identifier segment '${j}' contains characters outside [A-Za-z0-9_]`)}function ze(p,B,w=[]){let j=typeof p==="object"&&p!==null?p.parameters??p.values:void 0;if(kt(p,w)||Array.isArray(j)&&j.length>0){let re=B.startsWith("whereRaw(")?", or use where(). Model.query().whereRaw(sql, ...bindings) is the builder that binds `?` values.":B.startsWith("orWhereRaw(")?", or use orWhere(). Model.query().orWhereRaw(sql, ...bindings) is the builder that binds `?` values.":".";throw TypeError(`[query-builder] ${B}: this method takes a single fragment and no bindings, so the argument(s) after it would be dropped. Interpolate values with the exported \`raw\` tagged template, which inlines them as escaped literals${re}`)}if(typeof p==="string")return Kt(B),p;if(p===null||p===void 0)throw TypeError(`[query-builder] ${B}: fragment must be a SqlFragment, got ${p}`);if(Fe(p))return p.raw;if(typeof p==="object"){let re=p;if(typeof re.raw==="string")return re.raw;if(typeof re.raw==="function"){let oe=re.raw();if(typeof oe==="string")return oe}if(typeof re.sql==="string")return re.sql;let N=String(p);if(N!=="[object Object]"&&N!=="[object Promise]")return N}throw TypeError(`[query-builder] ${B}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}function Jt(p,B){if(!B||B.length===0)return;if(e.dialect!=="postgres")return;if(/\$\d/.test(p))return;let w=X(p),j=`${B.length} binding${B.length===1?"":"s"}`,re=w>0?`the query binds them with ${w} \`?\` placeholder${w===1?"":"s"}, which Postgres reads as an operator rather than a parameter`:"the query contains no $n placeholder for them to bind to";throw TypeError(`[query-builder] unsafe(): ${j} supplied, but ${re}. Postgres numbers `+"its parameters, so write $1, $2 \u2026 in the order the bindings should bind: "+"unsafe('SELECT * FROM users WHERE email = $1 LIMIT 1', [email]). `?` is correct on SQLite and MySQL, which is why this call may work there.")}var Dt=new Set;function Kt(p){if(Dt.has(p))return;Dt.add(p),console.warn(`[query-builder] ${p}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function Rt(p,B=e.dialect){return n(B)?p.replace(/\\/g,"\\\\").replace(/'/g,"''"):p.replace(/'/g,"''")}function Ke(p){if(p===null)return"NULL";if(typeof p==="number"&&Number.isFinite(p))return String(p);if(typeof p==="boolean")return p?"1":"0";if(typeof p==="string")return`'${Rt(p)}'`;if(p instanceof Date)return`'${p.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof p}`)}function _t(p,B){let w=Array.isArray(p)?p:p?[p]:[],j=[];if(w.length)j.push(`PARTITION BY ${w.join(", ")}`);if(B&&B.length)j.push(`ORDER BY ${B.map(([re,N])=>`${re} ${N==="desc"?"DESC":"ASC"}`).join(", ")}`);return j.length?`OVER (${j.join(" ")})`:"OVER ()"}class Ot{cache=new Map;maxSize=100;get(p){let B=this.cache.get(p);if(!B)return null;if(Date.now()>B.expiresAt)return this.cache.delete(p),null;return this.cache.delete(p),this.cache.set(p,B),B.data}set(p,B,w){if(this.cache.has(p))this.cache.delete(p);if(this.cache.size>=this.maxSize){let j=Date.now(),re=!1;for(let[N,oe]of this.cache)if(j>oe.expiresAt){if(this.cache.delete(N),re=!0,this.cache.size<this.maxSize)break}if(!re){let N=this.cache.keys().next().value;if(N!==void 0)this.cache.delete(N)}}this.cache.set(p,{data:B,expiresAt:Date.now()+w})}clear(){this.cache.clear()}setMaxSize(p){this.maxSize=Math.max(0,Math.floor(p));while(this.cache.size>this.maxSize){let B=this.cache.keys().next().value;if(B===void 0)break;this.cache.delete(B)}}}var mt=new Ot,Et=new WeakMap,jt=0;function Ut(p,B,w){let j=Et.get(p);if(j===void 0)j=++jt,Et.set(p,j);let re=w.map((N)=>ArrayBuffer.isView(N)?["view",St.isBuffer(N)?"Buffer":Object.prototype.toString.call(N),St.from(N.buffer,N.byteOffset,N.byteLength).toString("base64")]:["value",Mt(N).toString("base64")]);return`${j}\x00${B}\x00${JSON.stringify(re)}`}function Vt(p){let B=String(p?.message||"").toLowerCase();return B.includes("deadlock")||B.includes("serialization failure")||B.includes("could not serialize access")||B.includes("deadlock found when trying to get lock")||B.includes("lock wait timeout exceeded")||B.includes("database is locked")||B.includes("busy")}function Gt(p,B){if(!B||B.length===0)return!1;let w=p&&(p.code||p.sqlState||p.sqlstate);if(!w)return!1;return B.includes(w)}function Yt(p){return new Promise((B)=>setTimeout(B,p))}var bt=new Map,zt=500,Xt=[{key:"GROUP_BY",pattern:/GROUP\s+BY\b/iy},{key:"ORDER_BY",pattern:/ORDER\s+BY\b/iy},{key:"HAVING",pattern:/HAVING\b/iy},{key:"OFFSET",pattern:/OFFSET\b/iy},{key:"LIMIT",pattern:/LIMIT\b/iy},{key:"WHERE",pattern:/WHERE\b/iy}],Zt=[{key:"tail",pattern:/GROUP\s+BY\b/iy},{key:"tail",pattern:/ORDER\s+BY\b/iy},{key:"tail",pattern:/HAVING\b/iy},{key:"tail",pattern:/LIMIT\b/iy},{key:"tail",pattern:/OFFSET\b/iy},{key:"tail",pattern:/WINDOW\b/iy},{key:"tail",pattern:/UNION\b/iy},{key:"tail",pattern:/INTERSECT\b/iy},{key:"tail",pattern:/EXCEPT\b/iy},{key:"tail",pattern:/FOR\s+UPDATE\b/iy},{key:"tail",pattern:/FOR\s+SHARE\b/iy},{key:"tail",pattern:/LOCK\s+IN\s+SHARE\s+MODE\b/iy}],tn=[{key:"cut",pattern:/GROUP\s+BY\b/iy},{key:"cut",pattern:/ORDER\s+BY\b/iy},{key:"cut",pattern:/WHERE\b/iy},{key:"cut",pattern:/HAVING\b/iy},{key:"cut",pattern:/LIMIT\b/iy},{key:"cut",pattern:/OFFSET\b/iy},{key:"cut",pattern:/UNION\b/iy}];function Xe(p){let B=bt.get(p);if(B!==void 0)return B;let w=nn(p);if(bt.size>=zt)bt.clear();return bt.set(p,w),w}function nn(p){let B=qe(p,Xt);if(B.length<=1)return p;let w=p.slice(0,B[0].start).trimEnd(),j={};for(let oe=0;oe<B.length;oe++){let Ee=B[oe].start,pe=oe+1<B.length?B[oe+1].start:p.length,be=p.slice(Ee,pe).trim();if(!j[B[oe].key])j[B[oe].key]=[];j[B[oe].key].push(be)}let N=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((oe)=>j[oe]).map((oe)=>j[oe].join(" ")).join(" ");return N?`${w} ${N}`:w}function rn(p,B){let w=Math.max(1,B?.baseMs??50),j=Math.max(1,B?.factor??2),re=Math.max(w,B?.maxMs??2000),N=Math.min(re,w*j**Math.max(0,p-1));if(B?.jitter)N=Math.min(re,N*(0.9+Math.random()*0.2));return Math.floor(N)}function i(p){let B=p?.sql??b(),w=p?.meta,j=p?.schema,re;function N(h,g){let d=B.unsafe(h,g);if(typeof d.sql!=="string")re??=new WeakMap,re.set(d,{sql:h,params:g?.slice()});return d}let oe,Ee=(h,g)=>{let d=w?.temporalColumns?.[h];if(!d||d.length===0||!n(e.dialect))return g;return g.map((y)=>{let A=null;for(let f of d){if(!(f in y))continue;let Y=Ct(y[f]);if(Y!==y[f])A=A??{...y},A[f]=Y}return A??y})};function pe(h){if(typeof h==="number")return h;let g=String(h),d=7;for(let y=0;y<g.length;y++)d=d*31+g.charCodeAt(y)|0;return Math.abs(d)}function be(){if(!p?.hooks)return e.hooks;return{...e.hooks,...p.hooks}}let He=new Map;function Ve(h){if(Array.isArray(h)){let[f,Y,v]=h;F(f,"where(column)");let K=String(f);switch(Y){case"in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} IN (${q})`,v)}return N(`${K} IN (${t(1)})`,[v]);case"not in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} NOT IN (${q})`,v)}return N(`${K} NOT IN (${t(1)})`,[v]);case"like":return N(`${K} LIKE ${t(1)}`,[v]);case"is":case"is not":{if(v!==null&&v!==void 0)throw TypeError(`[query-builder] where(..., '${Y}', ?): operator '${Y}' only accepts NULL/undefined as value, got ${typeof v} (${String(v)})`);return N(`${K} IS ${Y==="is not"?"NOT ":""}NULL`)}case"!=":return N(`${K} <> ${t(1)}`,[v]);case"<":case">":case"<=":case">=":case"=":return N(`${K} ${Y} ${t(1)}`,[v]);default:throw TypeError(`[query-builder] where(..., '${String(Y)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in h)return h.raw;let g=Object.keys(h);if(g.length===0)return N("");let d=[],y=[],A=1;for(let f of g){F(f,"where(object key)");let Y=h[f];if(Array.isArray(Y)){let v=s(Y.length,A);d.push(`${f} IN (${v})`),y.push(...Y),A+=Y.length}else d.push(`${f} = ${t(A++)}`),y.push(Y)}return N(d.join(" AND "),y)}function et(h,g,d){if(!d)return g;let y=Ve(d);return B`${g} WHERE ${y}`}function tt(h){let g=re?.get(h);if(g)return g.sql;let d=e.debug?.captureText;if(e.debug)e.debug.captureText=!0;let y=String(h);if(e.debug)e.debug.captureText=d;return y}function ct(h){let g=re?.get(h);if(g)return g.params;if(!h||typeof h!=="object")return;if(Array.isArray(h.values))return h.values;if(Array.isArray(h.parameters))return h.parameters;if(Array.isArray(h.params))return h.params;return}function ne(h,g,d){let y=be(),A=y?.slowQueryThresholdMs,f=A!=null&&A>=0,Y=Boolean(y?.onSlowQuery||f),v=y&&(y.onQueryStart||y.onQueryEnd||y.onQueryError||y.startSpan||Y),K=d?.timeoutMs&&d.timeoutMs>0||d?.signal;if(!v&&!K)return h.execute();let q=tt(h),R=ct(h),J=Date.now(),k;try{if(y?.onQueryStart?.({sql:q,params:R,kind:g}),y?.startSpan)k=y.startSpan({sql:q,params:R,kind:g})}catch{}let I=!1,U=(V,ee,M=Boolean(V))=>{if(I)return;I=!0;let H=Date.now()-J;try{if(M)y?.onQueryError?.({sql:q,params:R,error:V,durationMs:H,kind:g});else if(y?.onQueryEnd?.({sql:q,params:R,durationMs:H,rowCount:ee,kind:g}),f&&H>=A)if(y?.onSlowQuery)y.onSlowQuery({sql:q,params:R,durationMs:H,kind:g});else console.warn(`[query-builder] slow query (${H}ms >= ${A}ms): ${q}`)}catch{}try{k?.end(V)}catch{}};if(typeof h.executeSync==="function"){let V,ee,M=!1;try{V=h.executeSync()}catch(te){ee=te,M=!0}if(d?.signal?.aborted){try{h.cancel?.()}catch{}ee=Object.assign(Error("Query aborted"),{code:"EBQBABORT"}),M=!0}if(M)return U(ee,void 0,!0),Promise.reject(ee);let H=Array.isArray(V)?V.length:typeof V==="number"?V:void 0;return U(void 0,H),Promise.resolve(V)}let W=h.execute(),_=[W],G;if(d?.timeoutMs&&d.timeoutMs>0){let V=new Promise((ee,M)=>{G=setTimeout(()=>{try{h.cancel?.()}catch{}let H=Error(`Query timed out after ${d.timeoutMs}ms`);H.code="EBQBTIMEOUT",M(H)},d.timeoutMs)});_.push(V)}if(d?.signal){if(d.signal.aborted){try{h.cancel?.()}catch{}let ee=Error("Query aborted");return ee.code="EBQBABORT",U(ee),Promise.reject(ee)}let V=()=>{try{h.cancel?.()}catch{}};d.signal.addEventListener("abort",V,{once:!0}),W.finally(()=>{d.signal?.removeEventListener("abort",V)})}return Promise.race(_).then((V)=>{clearTimeout(G);let ee=Array.isArray(V)?V.length:typeof V==="number"?V:void 0;return U(void 0,ee),V}).catch((V)=>{throw clearTimeout(G),U(V),V})}function Qe(h){if(typeof h==="number")return Number.isFinite(h)?h:0;if(typeof h==="bigint")return Number(h);if(!h||typeof h!=="object")return 0;let g=h;for(let d of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(g[d]!==void 0&&g[d]!==null)return Qe(g[d]);if(Array.isArray(h))return h.reduce((d,y)=>d+Qe(y),0);return 0}function xe(h,g){let d=g??tt(h);return{sql:d,toString:()=>d,execute:()=>h.execute(),values:()=>h.values(),raw:()=>h.raw()}}function Je(h,g){let d=B,y=g&&g.length>0?`SELECT ${g.join(", ")} FROM ${String(h)}`:`SELECT * FROM ${String(h)}`,A=[],f=[],Y=!1,v=!1,K=!1,q=null,R=()=>{if(q===null){let a=Xe(W());q=f.length>0?N(a,f):N(a)}return q},J=(a="",o="",u=[])=>N(`${a}${Xe(W())}${o}`,[...f,...u]),k=(a,o)=>{A.push({conn:a,sql:o}),q=null},I=(a,o)=>{k(a==="OR"?"OR":"AND",o)},U=(a)=>{let o=qe(a,Zt,1);return o.length>0?o[0].start:-1},W=(a)=>{let o=D(a?[...A,a]:A);if(!o)return y;if(Y)return`${y} ${v?"AND":"WHERE"} ${o}`;let u=U(y);return u>=0?`${y.slice(0,u)}WHERE ${o} ${y.slice(u)}`:`${y} WHERE ${o}`},_=(a,o,u,T)=>{let S=typeof u?.__sqlState==="function"?u.__sqlState():void 0,O;if(S){let C=f.length;O=C>0&&e.dialect==="postgres"?S.sql.replace(/\$(\d+)/g,(L,Q)=>`$${Number(Q)+C}`):S.sql,f.push(...S.params)}else O=String(u.toSQL());k(a,`${o} ${T?"NOT IN":"IN"} (${O})`)},G=(a,o)=>{let u=Je(h);o(u);let T=u.__whereState?.();if(!T||!T.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let S=f.length,O=S>0&&e.dialect==="postgres"?T.body.replace(/\$(\d+)/g,(C,L)=>`$${Number(L)+S}`):T.body;f.push(...T.params),k(a,`(${O})`)},V=(a,o,u,T,S,O)=>{if(typeof T==="string"&&S!==void 0){F(String(T),`${u}(column)`),$e(S,`${u}(operator)`);let C=Ue(String(T),String(S),O,u);if(C)return k(o,C),a;let L=f.length+1;return f.push(O),k(o,`${String(T)} ${String(S)} ${t(L)}`),a}if(Array.isArray(T)){let[C,L,Q]=T,x=String(C);F(x,`${u}(column)`);let P=$e(L,`${u}(operator)`);if(P==="in"||P==="not in"){let z=Array.isArray(Q)?Q:[Q],ae=s(z.length,f.length+1),we=l(c(x),z,P==="not in",ae);f.push(...z),k(o,we)}else{let z=Ue(x,P,Q,u);if(z)return k(o,z),a;let ae=f.length+1;f.push(Q),k(o,`${x} ${P} ${t(ae)}`)}return a}if(typeof T==="function")return G(o,T),a;if(it(T))lt(`${u}(expr)`);if(Ge(T)){let C=Ye(T,f.length+1);return f.push(...C.parameters),k(o,C.text),a}if(T&&typeof T==="object"&&!("raw"in T)){let C=[];for(let L of Object.keys(T)){F(L,`${u}(column)`);let Q=T[L];if(Array.isArray(Q)){let x=s(Q.length,f.length+1);C.push(l(c(L),Q,!1,x)),f.push(...Q)}else{let x=f.length+1;C.push(`${L} = ${t(x)}`),f.push(Q)}}if(C.length>0)k(o,C.length>1?`(${C.join(" AND ")})`:C[0]);return a}if(T&&typeof T.raw<"u")return k(o,T.raw),a;return a},ee=(a,o)=>{if(A.length>0)y=W(),A.length=0;Y=!0;let u=o.__rawState?.();if(u){let T=f.length,S=e.dialect==="postgres"?u.sql.replace(/\$(\d+)/g,(O,C)=>`$${Number(C)+T}`):u.sql;y+=` ${a} ${S}`,f.push(...u.params),v=o.__hasPredicate?.()??ye.WHERE.test(S)}else{let T=String(o.toSQL());y+=` ${a} ${T}`,v=o.__hasPredicate?.()??ye.WHERE.test(T)}q=null},M=(a)=>{let o=qe(y,tn,1),u=o.length>0?o[0].start:-1;y=u>=0?`${y.slice(0,u)}${a} ${y.slice(u)}`:`${y} ${a}`,q=null},H=new Set,te,Z,ce=!1,me=!1,Ie=!1,Le=new Map,ve=new Set,dt=60000,he=(a)=>m(e.relations.singularizeStrategy)(a),Ce=(a)=>{if(!w)return null;return E(w,String(h),a,{singularize:he,models:w.models})},nt=(a)=>{if(!a||typeof a!=="object"||ve.size===0)return a;let o;for(let u of Object.keys(a))if(u.startsWith("pivot_")){if(!o)o={};o[u.slice(6)]=a[u],delete a[u]}if(o)a.pivot=o;return a},rt=(a)=>{if(ve.size===0||!a)return a;if(Array.isArray(a))for(let o=0;o<a.length;o++)nt(a[o]);else nt(a);return a},st=(a)=>{if(!w)return;if(H.has(a.pivotTable))return;let o=String(h),u=w.primaryKeys[o]??"id";F(a.pivotTable,"wherePivot auto-join (pivot table)"),F(a.fkParent,"wherePivot auto-join (parent FK)"),F(o,"wherePivot auto-join (parent table)"),F(u,"wherePivot auto-join (parent PK)"),q=d`${R()} LEFT JOIN ${d(a.pivotTable)} ON ${d(`${a.pivotTable}.${a.fkParent}`)} = ${d(`${o}.${u}`)}`,y=`${y} LEFT JOIN ${a.pivotTable} ON ${a.pivotTable}.${a.fkParent} = ${o}.${u}`,H.add(a.pivotTable)},at=(a)=>{if(ye.SELECT_STAR.test(y))y=y.replace(ye.SELECT_STAR,`SELECT *, ${a}`);else if(ye.SELECT.test(y))y=y.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);let o=String(R());if(ye.SELECT_STAR.test(o)){let u=o.replace(ye.SELECT_STAR,`SELECT *, ${a}`);q=N(u)}else if(ye.SELECT.test(o)){if(ye.SELECT_FROM.exec(o)){let T=o.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);q=N(T)}}},Me=(a,o,u,T)=>{at(`${a} ${_t(u,T)} AS ${o}`)},yt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${a.endsWith("s")?a.slice(0,-1):a}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${S} = ${a}.${u}`;if(T){let L=T({where:(Q,x,P)=>(F(Q,"relationship subquery condition"),`${o}.${Q} ${$e(x,"whereHas callback")} ${Ke(P)}`)});if(L)O+=` AND ${L}`}return O},Tt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${o.endsWith("s")?o.slice(0,-1):o}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${u} = ${a}.${S}`;if(T){let L=T({where:(Q,x,P)=>(F(Q,"relationship subquery condition"),`${o}.${Q} ${$e(x,"whereHas callback")} ${Ke(P)}`)});if(L)O+=` AND ${L}`}return O},ht=(a,o,u,T,S,O)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)"),F(T,"relationship subquery (target primary key)");let C=O&&w?E(w,a,O,{singularize:he,models:w.models}):null,L=he(a),Q=he(o),x=C?.pivotTable??[L,Q].sort().join("_"),P=C?.fkParent??`${L}_id`,z=C?.fkRelated??`${Q}_id`;F(x,"relationship subquery (pivot table)"),F(P,"relationship subquery (foreign key A)"),F(z,"relationship subquery (foreign key B)");let ae=`SELECT 1 FROM ${x} JOIN ${o} ON ${o}.${T} = ${x}.${z} WHERE ${x}.${P} = ${a}.${u}`;if(S){let se=S({where:(Se,ke,Oe)=>(F(Se,"relationship subquery condition"),`${o}.${Se} ${$e(ke,"whereHas callback")} ${Ke(Oe)}`)});if(se)ae+=` AND ${se}`}return ae},Nt=(a,o,u)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let T=`${a.endsWith("s")?a.slice(0,-1):a}_id`;return F(T,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${o} WHERE ${o}.${T} = ${a}.${u})`},At=(a,o,u,T)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let S=T&&w?E(w,a,T,{singularize:he,models:w.models}):null,O=he(a),C=he(o),L=S?.pivotTable??[O,C].sort().join("_"),Q=S?.fkParent??`${O}_id`;return F(L,"withCount (pivot table)"),F(Q,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${L} WHERE ${L}.${Q} = ${a}.${u})`},gt=(a,o,u)=>{if(!w)return;F(u,`with${a[0]}${a.slice(1).toLowerCase()} (column)`);let T=String(h),S=w.relations?.[T];if(!S)return;let O=Object.entries(S).find(([se,Se])=>Se&&typeof Se==="object"&&(o in Se));if(!O)return;let[C,L]=O,Q=L[o],x=typeof Q==="string"?Q:Q?.model||Q?.target||Q,P=w.modelToTable[x]||x,z=w.primaryKeys[T]??"id";F(P,`with${a} (target table)`);let ae=`${a}(${P}.${u})`,we;if(C==="hasMany"||C==="hasOne"){let se=`${T.endsWith("s")?T.slice(0,-1):T}_id`;F(se,`with${a} (foreign key)`),we=`(SELECT ${ae} FROM ${P} WHERE ${P}.${se} = ${T}.${z})`}else if(C==="belongsToMany"){let se=w?E(w,T,o,{singularize:he,models:w.models}):null,Se=he(T),ke=he(P),Oe=se?.pivotTable??[Se,ke].sort().join("_"),Be=se?.fkParent??`${Se}_id`,ie=se?.fkRelated??`${ke}_id`,ot=w.primaryKeys[P]??"id";F(Oe,`with${a} (pivot table)`),F(Be,`with${a} (foreign key)`),F(ie,`with${a} (related key)`),we=`(SELECT ${ae} FROM ${Oe} JOIN ${P} ON ${P}.${ot} = ${Oe}.${ie} WHERE ${Oe}.${Be} = ${T}.${z})`}else return;at(`${we} AS ${o}_${a.toLowerCase()}_${u}`)},wt=()=>{if(Le.size===0)return;let a=[];for(let[o,u]of Le.entries()){let T=Ce(o);if(!T)continue;for(let O of u)F(O,"withPivot");let S=u.map((O)=>`${T.pivotTable}.${O} AS pivot_${O}`);a.push(...S)}if(a.length>0){let o=a.join(", ");at(o)}};return new Proxy({distinct(){return y=y.replace(/^SELECT\s+/i,"SELECT DISTINCT "),q=null,this},distinctOn(...a){let o=a.map(String).join(", ");return y=y.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${o}) `),q=null,this},selectRaw(a,...o){let u=ze(a,"selectRaw(fragment)",o),T=y.indexOf(" FROM ");if(T!==-1)y=`${y.substring(0,T)}, ${u}${y.substring(T)}`;else y+=`, ${u}`;return q=null,this},rowNumber(a="row_number",o,u){let T=[];if(o){let L=Array.isArray(o)?o:[o];T.push(`PARTITION BY ${L.join(", ")}`)}if(u&&u.length)T.push(`ORDER BY ${u.map(([L,Q])=>`${L} ${Q==="desc"?"DESC":"ASC"}`).join(", ")}`);let O=`ROW_NUMBER() ${T.length?`OVER (${T.join(" ")})`:"OVER ()"} AS ${a}`,C=y.indexOf(" FROM ");if(C!==-1)y=`${y.substring(0,C)}, ${O}${y.substring(C)}`;else y+=`, ${O}`;return q=null,this},denseRank(a="dense_rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([Q,x])=>`${Q} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`DENSE_RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${C}${y.substring(L)}`;else y+=`, ${C}`;return q=null,this},rank(a="rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([Q,x])=>`${Q} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${C}${y.substring(L)}`;else y+=`, ${C}`;return q=null,this},over(a,o,u={}){return Me(a,o,u.partitionBy,u.orderBy),this},lag(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return Me(`LAG(${u.join(", ")})`,o.alias??`${a}_lag`,o.partitionBy,o.orderBy),this},lead(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return Me(`LEAD(${u.join(", ")})`,o.alias??`${a}_lead`,o.partitionBy,o.orderBy),this},sumOver(a,o={}){return Me(`SUM(${a})`,o.alias??`${a}_sum`,o.partitionBy,o.orderBy),this},avgOver(a,o={}){return Me(`AVG(${a})`,o.alias??`${a}_avg`,o.partitionBy,o.orderBy),this},countOver(a="*",o={}){return Me(`COUNT(${a})`,o.alias??"count_over",o.partitionBy,o.orderBy),this},minOver(a,o={}){return Me(`MIN(${a})`,o.alias??`${a}_min`,o.partitionBy,o.orderBy),this},maxOver(a,o={}){return Me(`MAX(${a})`,o.alias??`${a}_max`,o.partitionBy,o.orderBy),this},firstValue(a,o={}){return Me(`FIRST_VALUE(${a})`,o.alias??`${a}_first`,o.partitionBy,o.orderBy),this},lastValue(a,o={}){return Me(`LAST_VALUE(${a})`,o.alias??`${a}_last`,o.partitionBy,o.orderBy),this},selectAll(){return this},select(a){if(!a)return this;let o=Array.isArray(a)?a:[a];if(o.length===0)return this;let u=o.map($t),T=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(y),S=T?T[1]:"",O=y.indexOf(" FROM ");if(O!==-1)y=`SELECT ${S}${u.join(", ")}${y.substring(O)}`;else y=`SELECT ${S}${u.join(", ")} FROM ${h}`;return q=null,this},addSelect(...a){if(!a.length)return this;let o=a.map($t),u=y.indexOf(" FROM ");if(u!==-1)y=`${y.substring(0,u)}, ${o.join(", ")}${y.substring(u)}`;else y+=`, ${o.join(", ")}`;return q=null,this},with(...a){if(!w||!a||a.length===0)return this;let o=[];for(let x of a){if(!x)continue;if(typeof x==="string")o.push({name:x});else if(typeof x==="object"&&!Array.isArray(x))for(let[P,z]of Object.entries(x))if(typeof z==="function")o.push({name:P,callback:z});else o.push({name:P})}if(o.length===0)return this;let u=e.relations.maxEagerLoad??50;if(o.length>u)throw Error(`[query-builder] Too many relationships to eager load (${o.length}). Maximum allowed: ${u}`);let T=String(h),S=new Set,O=new Set,C=new Map,L=(x)=>{let P=w.relations?.[x];if(!P)return[];return[...Object.keys(P.hasOne||{}),...Object.keys(P.hasMany||{}),...Object.keys(P.belongsTo||{}),...Object.keys(P.belongsToMany||{}),...Object.keys(P.hasOneThrough||{}),...Object.keys(P.hasManyThrough||{}),...Object.keys(P.morphOne||{}),...Object.keys(P.morphMany||{}),...Object.keys(P.morphToMany||{}),...Object.keys(P.morphedByMany||{})]},Q=(x,P,z=0,ae)=>{let we=e.relations.maxDepth??10;if(z>=we)throw Error(`[query-builder] Maximum relationship depth (${we}) exceeded at '${P}'. Consider using separate queries or increasing maxDepth.`);let se=w.relations?.[x];if(!se)return x;let Se=(le)=>{if(e.softDeletes?.enabled&&e.softDeletes?.defaultFilter){let ue=e.softDeletes.column||"deleted_at";return` AND ${le}.${ue} IS NULL`}return""},ke=(le)=>{if(!ae)return"";let ue=[],ge=(de,Ne,We)=>{F(String(de),"with() constraint column");let Ze=$e(Ne,"with() constraint operator");ue.push(`${le}.${String(de)} ${Ze} ${Ke(We)}`)},Te=(de)=>()=>{throw Error(`[query-builder] with('${P}', ...): ${de} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},fe={where:(de,Ne,We)=>{if(Array.isArray(de))ge(de[0],de[1],de[2]);else if(de&&typeof de==="object")for(let Ze of Object.keys(de))ge(Ze,"=",de[Ze]);else if(Ne!==void 0&&We!==void 0)ge(de,Ne,We);else if(Ne!==void 0)ge(de,"=",Ne);return fe},whereIn:(de,Ne)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IN (${Ne.map(Ke).join(", ")})`),fe),whereNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NULL`),fe),whereNotNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NOT NULL`),fe),orderBy:Te("orderBy()"),limit:Te("limit()"),offset:Te("offset()"),take:Te("take()")};return ae(fe),ue.length?` AND ${ue.join(" AND ")}`:""},Oe=()=>{let le=(Te)=>{let fe=Te?.[P];return fe?w.modelToTable[fe]:void 0},ue=(Te)=>{let fe=Te?.[P],de=typeof fe==="string"?fe:fe?.model;return de?w.modelToTable[de]:void 0},ge=(Te)=>{let fe=Te?.[P];return fe?.target?w.modelToTable[fe.target]:void 0};return le(se?.hasOne)||le(se?.hasMany)||le(se?.belongsTo)||ue(se?.belongsToMany)||ge(se?.hasOneThrough)||ge(se?.hasManyThrough)||le(se?.morphOne)||le(se?.morphMany)||le(se?.morphToMany)||le(se?.morphedByMany)},Be=Oe()??(w.modelToTable[P]||w.tableToModel[P]?w.modelToTable[P]??P:P),ie=String(Be);if(!Be||!Oe()&&!w.modelToTable[P]&&!w.tableToModel[P]){let le=L(x);if(le.length>0&&!le.includes(P)){let ue=` Available relationships: ${le.join(", ")}`;throw Error(`[query-builder] Relationship '${P}' not found on table '${x}'.${ue}`)}}if(e.relations.detectCycles!==!1){let le=`${x}->${ie}`;if(S.has(le))throw Error(`[query-builder] Circular relationship detected: ${le}. This would cause an infinite loop.`);S.add(le)}if(!ie||ie===x)return x;let ot=se?.hasOneThrough?.[P]||se?.hasManyThrough?.[P];if(ot){let{through:le,target:ue}=ot,ge=w.modelToTable[le]||le,Te=w.modelToTable[ue]||ue,fe=w.primaryKeys[x]??"id",de=w.primaryKeys[ge]??"id",Ne=`${he(x)}_id`,We=`${he(ge)}_id`;return M(`LEFT JOIN ${ge} ON ${ge}.${Ne} = ${x}.${fe} LEFT JOIN ${Te} ON ${Te}.${We} = ${ge}.${de}`),H.add(ge),H.add(Te),Te}if(Boolean(se?.belongsToMany?.[P])){let le=E(w,x,P,{singularize:he,models:w.models}),ue=le?.pivotTable??[he(x),he(ie)].sort().join("_"),ge=w.primaryKeys[x]??"id",Te=w.primaryKeys[ie]??"id",fe=le?.fkParent??`${he(x)}_id`,de=le?.fkRelated??`${he(ie)}_id`;return M(`LEFT JOIN ${ue} ON ${ue}.${fe} = ${x}.${ge} LEFT JOIN ${ie} ON ${ie}.${Te} = ${ue}.${de}${ke(ie)}`),H.add(ue),H.add(ie),ie}if(Boolean(se?.morphToMany?.[P])){let le=P,ue=`${he(ie)}_${le}`,ge=w.primaryKeys[x]??"id",Te=w.primaryKeys[ie]??"id",fe=`${le}_type`,de=`${le}_id`,Ne=`${he(ie)}_id`,We=Ke(w.tableToModel[x]||x);return M(`LEFT JOIN ${ue} ON ${ue}.${de} = ${x}.${ge} AND ${ue}.${fe} = ${We} LEFT JOIN ${ie} ON ${ie}.${Te} = ${ue}.${Ne}`),H.add(ue),H.add(ie),ie}if(Boolean(se?.morphedByMany?.[P])){let le=se.morphedByMany?.[P]||P,ue=w.modelToTable[le]||le,ge=he(x),Te=`${he(ue)}_${ge}`,fe=w.primaryKeys[x]??"id",de=w.primaryKeys[ue]??"id",Ne=`${ge}_type`,We=`${ge}_id`,Ze=`${he(ue)}_id`,Qt=Ke(w.tableToModel[ue]||ue);return M(`LEFT JOIN ${Te} ON ${Te}.${Ze} = ${x}.${fe} LEFT JOIN ${ue} ON ${ue}.${de} = ${Te}.${We} AND ${Te}.${Ne} = ${Qt}`),H.add(Te),H.add(ue),ue}if(Boolean(se?.belongsTo?.[P])){let le=`${he(ie)}_id`,ue=w.primaryKeys[ie]??"id";return M(`LEFT JOIN ${ie} ON ${x}.${le} = ${ie}.${ue}${ke(ie)}`),H.add(ie),ie}let It=Boolean(se?.morphOne?.[P]),xt=Boolean(se?.morphMany?.[P]);if(It||xt){let le=`${P}_type`,ue=`${P}_id`,ge=w.primaryKeys[x]??"id",Te=Ke(w.tableToModel[x]||x);return M(`LEFT JOIN ${ie} ON ${ie}.${ue} = ${x}.${ge} AND ${ie}.${le} = ${Te}`),H.add(ie),ie}let Lt=`${he(x)}_id`,Pt=w.primaryKeys[x]??"id",qt=`${Se(ie)}${ke(ie)}`;return M(`LEFT JOIN ${ie} ON ${ie}.${Lt} = ${x}.${Pt}${qt}`),H.add(ie),ie};for(let x of o){let P=x.name.trim();if(x.callback)C.set(P,x.callback);let z=P.split("."),ae=T,we=0;for(let se of z){if(!se||se.trim().length===0)continue;let Se=se.trim(),ke=C.get(Se);ae=Q(ae,Se,we,ke)||ae,we++}O.add(P)}if(Le.size>0){let x=[];for(let[P,z]of Le.entries()){let ae=Ce(P);if(!ae)continue;let we=z.map((se)=>`${ae.pivotTable}.${se} AS pivot_${se}`);x.push(...we)}if(x.length>0){let P=x.join(", ");at(P)}}return q=null,this},whereHas(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,C]=S,L=C[a],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P;if(O==="hasMany"||O==="hasOne"){let z=w.primaryKeys[u]??"id";P=yt(u,x,z,o)}else if(O==="belongsTo"){let z=w.primaryKeys[x]??"id";P=Tt(u,x,z,o)}else if(O==="belongsToMany"){let z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";P=ht(u,x,z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereHas`);return I("WHERE",`EXISTS (${P})`),this},whereDoesntHave(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,C]=S,L=C[a],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P;if(O==="hasMany"||O==="hasOne"){let z=w.primaryKeys[u]??"id";P=yt(u,x,z,o)}else if(O==="belongsTo"){let z=w.primaryKeys[x]??"id";P=Tt(u,x,z,o)}else if(O==="belongsToMany"){let z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";P=ht(u,x,z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereDoesntHave`);return I("WHERE",`NOT EXISTS (${P})`),this},has(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([P,z])=>z&&typeof z==="object"&&(a in z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,C=O[a],L=typeof C==="string"?C:C?.model||C?.target||C,Q=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let P=w.primaryKeys[o]??"id";x=yt(o,Q,P)}else if(S==="belongsTo"){let P=w.primaryKeys[Q]??"id";x=Tt(o,Q,P)}else if(S==="belongsToMany"){let P=w.primaryKeys[o]??"id",z=w.primaryKeys[Q]??"id";x=ht(o,Q,P,z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for has`);return I("WHERE",`EXISTS (${x})`),this},doesntHave(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([P,z])=>z&&typeof z==="object"&&(a in z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,C=O[a],L=typeof C==="string"?C:C?.model||C?.target||C,Q=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let P=w.primaryKeys[o]??"id";x=yt(o,Q,P)}else if(S==="belongsTo"){let P=w.primaryKeys[Q]??"id";x=Tt(o,Q,P)}else if(S==="belongsToMany"){let P=w.primaryKeys[o]??"id",z=w.primaryKeys[Q]??"id";x=ht(o,Q,P,z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for doesntHave`);return I("WHERE",`NOT EXISTS (${x})`),this},withCount(...a){if(!w||!a||a.length===0)return this;let o=String(h);for(let u of a){let T=w.relations?.[o];if(!T)continue;let S=Object.entries(T).find(([we,se])=>se&&typeof se==="object"&&(u in se));if(!S)continue;let[O,C]=S,L=C[u],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P=w.primaryKeys[o]??"id",z;if(O==="hasMany"||O==="hasOne")z=Nt(o,x,P);else if(O==="belongsToMany")z=At(o,x,P,u);else continue;let ae=`${u}_count`;at(`${z} AS ${ae}`)}return this},withSum(a,o){return gt("SUM",a,o),this},withAvg(a,o){return gt("AVG",a,o),this},withMax(a,o){return gt("MAX",a,o),this},withMin(a,o){return gt("MIN",a,o),this},applyPivotColumns(){return wt(),this},withPivot(a,...o){if(!w)return this;let u=String(h),T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${u}'`);let S=o&&o.length>0?o:T.hasConfig?T.pivotColumns:[];if(S.length===0)return this;if(Le.set(a,S),T.hasConfig)ve.add(a);return wt(),this},wherePivot(a,o,u,T){if(!w)return this;let S=Ce(a);if(!S)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(S.pivotTable,"wherePivot (pivot table)"),F(o,"wherePivot (column)"),st(S);let O=T===void 0?"=":String(u),C=T===void 0?u:T,L=f.length+1,Q=`${S.pivotTable}.${o} ${O} ${t(L)}`;if(f.push(C),k("AND",Q),S.hasConfig)ve.add(a);return this},wherePivotIn(a,o,u){if(!w||!Array.isArray(u))return this;let T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotIn (pivot table)"),F(o,"wherePivotIn (column)"),st(T);let S=s(u.length,f.length+1),O=l(`${T.pivotTable}.${o}`,u,!1,S);if(f.push(...u),k("AND",O),T.hasConfig)ve.add(a);return this},wherePivotNotIn(a,o,u){if(!w||!Array.isArray(u)||u.length===0)return this;let T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotNotIn (pivot table)"),F(o,"wherePivotNotIn (column)"),st(T);let S=s(u.length,f.length+1),O=`${T.pivotTable}.${o} NOT IN (${S})`;if(f.push(...u),k("AND",O),T.hasConfig)ve.add(a);return this},wherePivotNull(a,o){if(!w)return this;let u=Ce(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNull (pivot table)"),F(o,"wherePivotNull (column)"),st(u),k("AND",`${u.pivotTable}.${o} IS NULL`),u.hasConfig)ve.add(a);return this},wherePivotNotNull(a,o){if(!w)return this;let u=Ce(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNotNull (pivot table)"),F(o,"wherePivotNotNull (column)"),st(u),k("AND",`${u.pivotTable}.${o} IS NOT NULL`),u.hasConfig)ve.add(a);return this},where(a,o,u){if(typeof a==="string"&&o!==void 0){F(String(a),"where(column)"),$e(o,"where(operator)");let T=String(o).toLowerCase();if(T==="in"||T==="not in"){let C=Array.isArray(u)?u:[u],L=s(C.length,f.length+1),Q=l(c(String(a)),C,T==="not in",L);return f.push(...C),k("AND",Q),this}let S=Ue(c(String(a)),T,u,"where");if(S)return k("AND",S),this;let O=f.length+1;return f.push(u),k("AND",`${c(String(a))} ${String(o)} ${t(O)}`),this}if(Array.isArray(a)){let[T,S,O]=a,C=String(T);F(C,"where(column)");let L=$e(S,"where(operator)");if(L==="in"||L==="not in"){let Q=Array.isArray(O)?O:[O],x=s(Q.length,f.length+1),P=l(c(C),Q,L==="not in",x);f.push(...Q),k("AND",P)}else{let Q=Ue(c(C),L,O,"where");if(Q)return k("AND",Q),this;let x=f.length+1;f.push(O),k("AND",`${c(C)} ${L} ${t(x)}`)}return this}if(it(a))lt("where(expr)");if(Ge(a)){let T=Ye(a,f.length+1);return f.push(...T.parameters),k("AND",T.text),this}if(a&&typeof a==="object"&&!Fe(a)){let T=a,S=Object.keys(T),O=[];for(let C of S){F(C,"where(column)");let L=T[C];if(Array.isArray(L)){let Q=s(L.length,f.length+1);O.push(l(c(C),L,!1,Q)),f.push(...L)}else{let Q=f.length+1;O.push(`${c(C)} = ${t(Q)}`),f.push(L)}}if(O.length>0)k("AND",O.length>1?`(${O.join(" AND ")})`:O[0]);return this}if(Fe(a))return k("AND",a.raw),this;if(typeof a==="function")return G("AND",a),this;if(a===void 0||a===null)throw TypeError("where() was called with no condition.");if(typeof a==="string")throw TypeError(`where(${JSON.stringify(a)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof a}.`)},whereNull(a){return F(String(a),"whereNull(column)"),k("AND",`${String(a)} IS NULL`),this},whereNotNull(a){return F(String(a),"whereNotNull(column)"),k("AND",`${String(a)} IS NOT NULL`),this},orWhereNull(a){return F(String(a),"orWhereNull(column)"),k("OR",`${String(a)} IS NULL`),this},orWhereNotNull(a){return F(String(a),"orWhereNotNull(column)"),k("OR",`${String(a)} IS NOT NULL`),this},whereBetween(a,o,u){F(String(a),"whereBetween(column)");let T=f.length+1;return f.push(o,u),k("AND",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},orWhereBetween(a,o,u){F(String(a),"orWhereBetween(column)");let T=f.length+1;return f.push(o,u),k("OR",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereExists(a){return k("AND",`EXISTS (${a.toSQL()})`),this},orWhereExists(a){return k("OR",`EXISTS (${a.toSQL()})`),this},whereGroup(a){return G("AND",a),this},orWhereGroup(a){return G("OR",a),this},__whereState(){return{body:D(A),params:[...f]}},__sqlState(){return{sql:Xe(W()),params:[...f]}},whereJsonContains(a,o){F(String(a),"whereJsonContains(column)");let u=e.dialect,T=f.length+1;if(u==="postgres"){let O=typeof o==="number"||typeof o==="boolean"?`to_jsonb(${t(T)})`:t(T);if(e.sql?.jsonContainsMode==="function")k("AND",`jsonb_contains(${a}, ${O})`);else k("AND",`${a} @> ${O}`);f.push(o)}else if(n(u))k("AND",`JSON_CONTAINS(${a}, ${t(T)})`),f.push(JSON.stringify(o));else if(Array.isArray(o)){let S=o.map((O,C)=>`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T+C)})`);k("AND",`(${S.join(" AND ")})`);for(let O of o)f.push(O)}else if(o!==null&&typeof o==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else k("AND",`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T)})`),f.push(o);return this},whereJsonPath(a,o,u){if($e(o,"whereJsonPath(op)"),typeof a!=="string"||a.length===0||a.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof a==="string"?`'${a.slice(0,32)}...'`:typeof a}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(a))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${a}' \u2014 contains characters outside the allowed JSON-path set`);let T=e.dialect,S=f.length+1;if(T==="postgres")k("AND",`${a} ${o} ${t(S)}`);else if(n(T))k("AND",`JSON_EXTRACT(${a}) ${o} ${t(S)}`);else k("AND",`json_extract(${a}) ${o} ${t(S)}`);return f.push(u),this},whereLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},whereNotLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} NOT ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereNotLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} NOT ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},whereAny(a,o,u){if(a.length===0)return k("AND",`(${Ht})`),this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" OR ")})`),this},whereAll(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" AND ")})`),this},whereNone(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`NOT (${S.join(" OR ")})`),this},whereNotBetween(a,o,u){F(String(a),"whereNotBetween(column)");let T=f.length+1;return f.push(o,u),k("AND",`${a} NOT BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereDate(a,o,u){F(a,"whereDate(column)");let T=u instanceof Date?u.toISOString():typeof u==="string"?u:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof u}`)})(),S=f.length+1;return f.push(T),k("AND",`${a} ${o} ${t(S)}`),this},whereRaw(a,...o){return k("AND",ze(a,"whereRaw(fragment)",o)),this},orWhereRaw(a,...o){return k("OR",ze(a,"orWhereRaw(fragment)",o)),this},whereColumn(a,o,u){return F(a,"whereColumn(left)"),F(u,"whereColumn(right)"),k("AND",`${a} ${o} ${u}`),this},orWhereColumn(a,o,u){return F(a,"orWhereColumn(left)"),F(u,"orWhereColumn(right)"),k("OR",`${a} ${o} ${u}`),this},whereIn(a,o){if(F(String(a),"whereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),k("AND",T)}else _("AND",a,o,!1);return this},orWhereIn(a,o){if(F(String(a),"orWhereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),k("OR",T)}else _("OR",a,o,!1);return this},whereNotIn(a,o){if(F(String(a),"whereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),k("AND",T)}else _("AND",a,o,!0);return this},orWhereNotIn(a,o){if(F(String(a),"orWhereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),k("OR",T)}else _("OR",a,o,!0);return this},whereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("AND",`(${o})`),this},orWhereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("OR",`(${o})`),this},andWhere(a,o,u){return V(this,"AND","andWhere",a,o,u)},orWhere(a,o,u){return V(this,"OR","orWhere",a,o,u)},orderBy(a,o="asc"){let u=o==="asc"?"ASC":"DESC",T=c(String(a));return y=ye.ORDER_BY.test(y)?`${y}, ${T} ${u}`:`${y} ORDER BY ${T} ${u}`,q=null,this},orderByDesc(a){return y=ye.ORDER_BY.test(y)?`${y}, ${a} DESC`:`${y} ORDER BY ${a} DESC`,q=null,this},inRandomOrder(){let a=e.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return y=ye.ORDER_BY.test(y)?`${y}, ${a}`:`${y} ORDER BY ${a}`,q=null,this},reorder(a,o="asc"){return y=y.replace(/ORDER BY[\s\S]*$/i,""),y+=` ORDER BY ${a} ${o==="asc"?"ASC":"DESC"}`,q=null,this},latest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} DESC`:`${y} ORDER BY ${o} DESC`,q=null,this},oldest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} ASC`:`${y} ORDER BY ${o} ASC`,q=null,this},limit(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${a}`);return y=ye.LIMIT.test(y)?y.replace(ye.LIMIT,` LIMIT ${a}`):`${y} LIMIT ${a}`,q=null,this},offset(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${a}`);return y=ye.OFFSET.test(y)?y.replace(ye.OFFSET,` OFFSET ${a}`):`${y} OFFSET ${a}`,q=null,this},join(a,o,u,T){return F(a,"join(table)"),Pe(o,"join(onLeft)"),Pe(T,"join(onRight)"),$e(u,"join(operator)"),M(`JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},joinSub(a,o,u,T,S){return F(o,"joinSub(alias)"),Pe(u,"joinSub(onLeft)"),Pe(S,"joinSub(onRight)"),$e(T,"joinSub(operator)"),M(`JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),H.add(o),this},innerJoin(a,o,u,T){return F(a,"innerJoin(table)"),Pe(o,"innerJoin(onLeft)"),Pe(T,"innerJoin(onRight)"),$e(u,"innerJoin(operator)"),M(`INNER JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},leftJoin(a,o,u,T){return F(a,"leftJoin(table)"),Pe(o,"leftJoin(onLeft)"),Pe(T,"leftJoin(onRight)"),$e(u,"leftJoin(operator)"),M(`LEFT JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},leftJoinSub(a,o,u,T,S){return F(o,"leftJoinSub(alias)"),Pe(u,"leftJoinSub(onLeft)"),Pe(S,"leftJoinSub(onRight)"),$e(T,"leftJoinSub(operator)"),M(`LEFT JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),H.add(o),this},rightJoin(a,o,u,T){return F(a,"rightJoin(table)"),Pe(o,"rightJoin(onLeft)"),Pe(T,"rightJoin(onRight)"),$e(u,"rightJoin(operator)"),M(`RIGHT JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},crossJoin(a){return F(a,"crossJoin(table)"),M(`CROSS JOIN ${a}`),H.add(a),this},crossJoinSub(a,o){return F(o,"crossJoinSub(alias)"),M(`CROSS JOIN (${String(a.toSQL())}) AS ${o}`),H.add(o),this},selectAllRelations(){if(!j)return this;let a=String(h),o=Object.keys(j[a]?.columns??{}),u=[];if(o.length>0)u.push(d`${d(a)}.*`);for(let T of H){let S=Object.keys(j[T]?.columns??{});for(let O of S){let C=e.aliasing.relationColumnAliasFormat==="camelCase"?`${T}_${O}`.replace(/_([a-z])/g,(L,Q)=>Q.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${T}.${O}`:`${T}_${O}`;u.push(d`${d(`${T}.${O}`)} AS ${d(C)}`)}}if(u.length>0){let T=o.length>0?`${a}.*`:"",S=[];for(let L of H){let Q=Object.keys(j[L]?.columns??{});for(let x of Q){let P=e.aliasing.relationColumnAliasFormat==="camelCase"?`${L}_${x}`.replace(/_([a-z])/g,(z,ae)=>ae.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${L}.${x}`:`${L}_${x}`;S.push(`${L}.${x} AS ${P}`)}}let O=[T,...S].filter(Boolean).join(", "),C=y.indexOf(" FROM ");if(C!==-1)y=`SELECT ${O}${y.substring(C)}`;else y=`SELECT ${O} FROM ${a}`;q=null}return this},groupBy(...a){if(a.length)y=ye.GROUP_BY.test(y)?`${y}, ${a.map((o)=>c(String(o))).join(", ")}`:`${y} GROUP BY ${a.map((o)=>c(String(o))).join(", ")}`,q=null;return this},groupByRaw(a,...o){let u=ze(a,"groupByRaw(fragment)",o);return y=ye.GROUP_BY.test(y)?`${y}, ${u}`:`${y} GROUP BY ${u}`,q=null,this},having(a){let o=K?"AND":"HAVING";if(Array.isArray(a)){let u=f.length+1;y=`${y} ${o} ${a[0]} ${a[1]} ${t(u)}`,f.push(a[2]),K=!0,q=null}else if(a&&typeof a==="object"&&!("raw"in a)){let u=Object.keys(a),T=u.length;if(T){let S=f.length,O=Array.from({length:T});for(let C=0;C<T;C++){let L=u[C];O[C]=`${L} = ${t(S+C+1)}`,f.push(a[L])}y=`${y} ${o} ${O.join(" AND ")}`,K=!0,q=null}}else if(a&&typeof a.raw<"u")y+=` ${o} ${a.raw}`,K=!0,q=null;return this},havingRaw(a,...o){let u=ze(a,"havingRaw(fragment)",o);return y+=` ${K?"AND":"HAVING"} ${u}`,K=!0,q=null,this},orderByRaw(a,...o){let u=ze(a,"orderByRaw(fragment)",o);return y=ye.ORDER_BY.test(y)?`${y}, ${u}`:`${y} ORDER BY ${u}`,q=null,this},$call(a){return a(this),this},union(a){return ee("UNION",a),this},unionAll(a){return ee("UNION ALL",a),this},intersect(a){return ee("INTERSECT",a),this},intersectAll(a){return ee("INTERSECT ALL",a),this},except(a){return ee("EXCEPT",a),this},exceptAll(a){return ee("EXCEPT ALL",a),this},forPage(a,o){let u=Math.max(1,Math.floor(a)),T=Math.max(1,Math.floor(o));return y+=` LIMIT ${T} OFFSET ${(u-1)*T}`,q=null,this},toSQL(){let a=Xe(W());return{sql:a,toString:()=>a,execute:()=>R().execute(),values:()=>R().values(),raw:()=>R().raw()}},async value(a){let o=J(""," LIMIT 1"),u=await ne(o,"select",{signal:Z,timeoutMs:te}),[T]=u;return T?.[a]},async pluck(a,o){let u=await ne(R(),"select",{signal:Z,timeoutMs:te});if(o){let T={};for(let S of u){let O=String(S?.[o]);if(Object.prototype.hasOwnProperty.call(T,O))throw Error(`[query-builder] pluck(${a}, ${o}): duplicate key '${O}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);T[O]=S?.[a]}return T}return u.map((T)=>T?.[a])},async exists(){let a=J("SELECT EXISTS (",") as e"),o=await ne(a,"select",{signal:Z,timeoutMs:te}),[u]=o;return Boolean(u?.e)},async doesntExist(){return!await this.exists()},async paginate(a,o=1,u={}){if(typeof a==="object"&&a!==null){let z=a;o=z.page??1,u=z.tx?{tx:z.tx}:{},a=z.perPage??10}if(!Number.isFinite(a)||a<=0||!Number.isInteger(a))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${a}`);if(!Number.isFinite(o)||o<1||!Number.isInteger(o))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${o}`);if(u.tx){let z=Xe(W()),ae=[...f],we=await u.tx.unsafe(`SELECT COUNT(*) as c FROM (${z}) as sub`,ae),se=Number(we?.[0]?.c??0),Se=Math.max(1,Math.ceil(se/a)),ke=Math.max(1,Math.min(o,Se)),Oe=(ke-1)*a;return{data:await u.tx.unsafe(`${z} LIMIT ${a} OFFSET ${Oe}`,ae),meta:{perPage:a,page:ke,total:se,lastPage:Se}}}let T=J("SELECT COUNT(*) as c FROM (",") as sub"),S=await ne(T,"select",{signal:Z,timeoutMs:te}),[O]=S,C=Number(O?.c??0),L=Math.max(1,Math.ceil(C/a)),Q=Math.max(1,Math.min(o,L)),x=(Q-1)*a;return{data:await ne(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a,x]),"select",{signal:Z,timeoutMs:te}),meta:{perPage:a,page:Q,total:C,lastPage:L}}},async simplePaginate(a,o=1){let u=Math.max(1,o),T=(u-1)*a,S=await ne(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a+1,T]),"select",{signal:Z,timeoutMs:te}),O=S.length>a;return{data:O?S.slice(0,a):S,meta:{perPage:a,page:u,hasMore:O}}},async cursorPaginate(a,o,u="id",T="asc"){if(!Number.isInteger(a)||a<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${a}`);let S=(Array.isArray(u)?u:[u]).map(String);for(let Be of S)F(Be,"cursorPaginate(column)");let O=T==="asc"?">":"<",C=T==="asc"?"ASC":"DESC",L=[...f],Q="";if(o!==void 0&&o!==null)if(Array.isArray(u)){let Be=o.map((ie)=>(L.push(ie),t(L.length)));Q=`(${S.join(", ")}) ${O} (${Be.join(", ")})`}else L.push(o),Q=`${S[0]} ${O} ${t(L.length)}`;let x=Xe(Q?W({conn:"AND",sql:Q}):W()),P=S.map((Be)=>`${Be} ${C}`).join(", ");if(Ft(x))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${P} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let z=L.length>0?N(`${x} ORDER BY ${P} LIMIT ${a+1}`,L):N(`${x} ORDER BY ${P} LIMIT ${a+1}`),ae=await ne(z,"select",{signal:Z,timeoutMs:te}),we=ae.length>a,se=ae.slice(0,a),Se=se[se.length-1],ke=we&&Se?Array.isArray(u)?u.map((Be)=>Se[Be]):Se[u]:null,Oe=se.length?Array.isArray(u)?u.map((Be)=>se[0]?.[Be]):se[0]?.[u]:null;return{data:se,meta:{perPage:a,nextCursor:ke??null,prevCursor:Oe}}},async chunk(a,o){let u=1;while(!0){let{data:T,meta:S}=await this.paginate(a,u);if(T.length===0)break;if(await o(T),u>=S.lastPage)break;u+=1}},async chunkById(a,o="id",u){let T;while(!0){let{data:S,meta:O}=await this.cursorPaginate(a,T,o,"asc");if(S.length===0)break;if(u)await u(S);if(T=O.nextCursor,!T)break}},async eachById(a,o="id",u){await this.chunkById(a,o,async(T)=>{for(let S of T)await u?.(S)})},withTimeout(a){return te=Math.max(1,Math.floor(a)),this},abort(a){return Z=a,this},withTrashed(){return ce=!0,me=!1,this},onlyTrashed(){ce=!0,me=!0;let a=e.softDeletes?.column||"deleted_at";return k("AND",`${h}.${a} IS NOT NULL`),this},scope(a,o){let u=String(h),S=w?.scopes?.[u]?.[a];if(S)return S(this,o);return this},when(a,o,u){if(a)return o(this);if(u)return u(this);return this},tap(a){return a(this),this},dump(){return console.log(String(R())),this},dd(){throw console.log(String(R())),Error("Dump and Die")},cache(a=60000){return dt=a,Ie=!0,this},async explain(){let a=J("EXPLAIN ");return await ne(a,"select",{signal:Z,timeoutMs:te})},simple(){return R().simple()},toText(){return W()},async get(){let a=be(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||ut(a));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let L=B._prepareStatement;if(L){let Q=L(W());return rt(f.length>0?Q.all(...f):Q.all())}}let u=W();if(q=f.length>0?N(u,f):N(u),!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let L=R()._stmt,Q=R()._params;if(L)return rt(Q&&Q.length>0?L.all(...Q):L.all());return rt(await R().execute())}if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z)return rt(await ne(R(),"select"));let T=R();if(e.softDeletes?.enabled&&e.softDeletes.defaultFilter&&!ce){let L=e.softDeletes.column,Q=String(h);if((j?Boolean(j[Q]?.columns?.[L]):!0)&&!ye.DELETED_AT.test(W()))I("WHERE",`${String(L)} IS ${me?"NOT ":""}NULL`),T=R()}let S=Ie&&!p?.inTransaction,O=S?Ut(B,W(),f):"";if(S){let L=mt.get(O);if(L)return L}let C=await ne(T,"select",{signal:Z,timeoutMs:te});if(S)mt.set(O,C,dt);return rt(C)},async executeTakeFirst(){let a=await ne(R(),"select",{signal:Z,timeoutMs:te});return nt(Array.isArray(a)?a[0]:a)},async executeTakeFirstOrThrow(){let a=await this.executeTakeFirst();if(!a)throw Error("Record not found");return a},async first(){let a=be(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||ut(a));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let S=B._prepareStatement;if(S){let O=W(),C=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,L=S(C),Q=f.length>0?L.all(...f):L.all();return nt(Q[0])}}let u=await ne(J(""," LIMIT 1"),"select",{signal:Z,timeoutMs:te}),[T]=u;return nt(T)},async firstOrFail(){let a=await this.first();if(!a)throw Error("Record not found");return a},async find(a){let o=w?.primaryKeys[String(h)]??"id",u=await ne(J("",` WHERE ${De(o)} = ${t(f.length+1)} LIMIT 1`,[a]),"select",{signal:Z,timeoutMs:te}),[T]=u;return T},async findOrFail(a){let o=await this.find(a);if(!o)throw Error("Record not found");return o},async findMany(a){let o=w?.primaryKeys[String(h)]??"id";return await ne(J("",` WHERE ${l(De(String(o)),a,!1,s(a.length,f.length+1))}`,a),"select",{signal:Z,timeoutMs:te})},async*lazy(){let a,o=w?.primaryKeys[String(h)]??"id";while(!0){let T=await(a==null?d`${R()} ORDER BY ${d(String(o))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(o))} > ${a} ORDER BY ${d(String(o))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(a=T[T.length-1]?.[o],a==null)break}},async*lazyById(){let a=w?.primaryKeys[String(h)]??"id",o;while(!0){let T=await(o==null?d`${R()} ORDER BY ${d(String(a))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(a))} > ${o} ORDER BY ${d(String(a))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(o=T[T.length-1]?.[a],o==null)break}},pipe(a){return a(this)},async count(){let a=W(),o=a.indexOf(" FROM "),u=/ GROUP BY /i.test(a),T;if(u)T=`SELECT COUNT(*) as c FROM (${a}) AS _bqb_count_sub`;else if(o!==-1)T=`SELECT COUNT(*) as c${a.substring(o)}`;else T=`SELECT COUNT(*) as c FROM ${h}`;let S=be(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||ut(S));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!O){let x=B._prepareStatement;if(x){let P=x(T),z=f.length>0?P.all(...f):P.all();return Number(z[0]?.c??0)}}let C=f.length>0?N(T,f):N(T),L=await ne(C,"select",{signal:Z,timeoutMs:te}),[Q]=L;return Number(Q?.c??0)},async avg(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT AVG(${a}) as a${o.substring(u)}`:`SELECT AVG(${a}) as a FROM ${h}`,S=be(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||ut(S));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!O){let x=B._prepareStatement;if(x){let P=x(T),z=f.length>0?P.all(...f):P.all();return Number(z[0]?.a??0)}}let C=f.length>0?N(T,f):N(T),L=await ne(C,"select",{signal:Z,timeoutMs:te}),[Q]=L;return Number(Q?.a??0)},async sum(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT SUM(${a}) as s${o.substring(u)}`:`SELECT SUM(${a}) as s FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return Number(C?.s??0)},async max(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MAX(${a}) as m${o.substring(u)}`:`SELECT MAX(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return C?.m},async min(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MIN(${a}) as m${o.substring(u)}`:`SELECT MIN(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return C?.m},lockForUpdate(){return y+=" FOR UPDATE",q=null,this},sharedLock(){let a=e.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return y+=` ${a}`,q=null,this},withCTE(a,o){return F(a,"withCTE(name)"),y=`WITH ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},withRecursive(a,o){return F(a,"withRecursive(name)"),y=`WITH RECURSIVE ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},execute(){return ne(R(),"select",{signal:Z,timeoutMs:te})},values(){return R().values()},toParams(){return[...f]},__rawState(){return{sql:Xe(W()),params:[...f]}},__hasPredicate(){return A.length>0||v},raw(){return R().raw()},get rows(){return},get row(){return},cancel(){try{R().cancel()}catch{}}},{get(a,o,u){let T=Reflect.get(a,o,u);if(T!==void 0)return T;if(typeof o==="string"&&(o.startsWith("where")||o.startsWith("orWhere")||o.startsWith("andWhere"))){let S=o.startsWith("orWhere"),O=o.startsWith("andWhere"),C=`${String(h)}|${o}`,L=He.get(C);if(L===void 0){let x=o.replace(/^(?:or|and)?where/i,"");if(!x)He.set(C,""),L="";else{let P=x.charAt(0).toLowerCase()+x.slice(1),z=x.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ae=j?Object.keys(j[String(h)]?.columns??{}):[];L=[z,P,P.toLowerCase()].find((we)=>ae.includes(we))??z,He.set(C,L)}}if(L==="")return()=>u;let Q=L;return(x)=>{if(Array.isArray(x)){let P=s(x.length,f.length+1);I(S?"OR":O?"AND":"WHERE",`${Q} IN (${P})`),f.push(...x)}else{let P=t(f.length+1);I(S?"OR":O?"AND":"WHERE",`${Q} = ${P}`),f.push(x)}return u}}return Reflect.get(a,o,u)}})}return{configure(h){return _e(h),this},id(h){if(!ye.IDENTIFIER.test(h))throw Error(`[query-builder] Invalid identifier: '${h}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(String(h))},ids(...h){for(let g of h)if(!ye.IDENTIFIER.test(g))throw Error(`[query-builder] Invalid identifier: '${g}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(h)},select(h,...g){return Je(h,g)},selectFrom(h){return Je(h)},selectFromSub(h,g){function d(R){return()=>{throw Error(`[query-builder] selectFromSub(...).${R}() is not supported. Apply ${R}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}F(String(g),"selectFromSub(alias)");let y=typeof h.__rawState==="function"?h.__rawState():null,A=h.toSQL(),f=y?.sql??(typeof A==="string"?A:A?.sql??String(A)),Y=y?.params??(Array.isArray(A?.values)?A.values:[]),v=`SELECT * FROM (${f}) AS ${String(g)}`,K=(R,J,k,I)=>{let U=[...R],W=(G,V,ee)=>{F(G,"selectFromSub where(column)");let M=$e(V,"selectFromSub where(operator)");if(M==="in"||M==="not in"){let te=Array.isArray(ee)?ee:[ee],Z=s(te.length,U.length+1);return U.push(...te),`${G} ${M.toUpperCase()} (${Z})`}let H=t(U.length+1);return U.push(ee),`${G} ${M} ${H}`},_;if(typeof J==="string"&&k!==void 0)_=W(J,k,I);else if(Array.isArray(J)&&J.length===3)_=W(J[0],J[1],J[2]);else if(J&&typeof J==="object"){let G=Object.entries(J).map(([V,ee])=>W(V,"=",ee));_=G.length>1?`(${G.join(" AND ")})`:G[0]}else return{clause:null,params:R};return{clause:_,params:U}};function q(R,J,k,I=""){let U=D(J),W=U?`${R} WHERE ${U}${I}`:`${R}${I}`,_=()=>k.length>0?N(W,k):N(W),G=(M,H,te,Z)=>{let ce=K(k,H,te,Z);return ce.clause===null?q(R,J,k,I):q(R,[...J,{conn:M,sql:ce.clause}],ce.params,I)},V=(M,H)=>{let te=[],Z=[...k],ce=(Le)=>(ve,dt,he)=>{let Ce=K(Z,ve,dt,he);if(Ce.clause!==null)te.push({conn:Le,sql:Ce.clause}),Z=Ce.params;return me},me={where:ce("AND"),andWhere:ce("AND"),orWhere:ce("OR")};H(me);let Ie=D(te);if(!Ie)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return q(R,[...J,{conn:M,sql:`(${Ie})`}],Z,I)},ee={distinct(){return q(R.replace(/^SELECT\s+/i,"SELECT DISTINCT "),J,k,I)},distinctOn(...M){let H=M.map(String).join(", ");return q(R.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${H}) `),J,k,I)},selectRaw(M,...H){let te=ze(M,"selectFromSub.selectRaw(fragment)",H),Z=R.indexOf(" FROM "),ce=Z!==-1?`${R.slice(0,Z)}, ${te}${R.slice(Z)}`:`${R}, ${te}`;return q(ce,J,k,I)},$call(M){return M(this)??this},where(M,H,te){return G("AND",M,H,te)},andWhere(M,H,te){return G("AND",M,H,te)},orWhere(M,H,te){return G("OR",M,H,te)},whereGroup(M){return V("AND",M)},orWhereGroup(M){return V("OR",M)},orderBy(M,H="asc"){F(String(M),"selectFromSub.orderBy(column)");let te=H==="asc"?"ASC":"DESC",Z=ye.ORDER_BY.test(I)?`${I}, ${M} ${te}`:`${I} ORDER BY ${M} ${te}`;return q(R,J,k,Z)},limit(M){if(!Number.isInteger(M)||M<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${M}`);let H=ye.LIMIT.test(I)?I.replace(ye.LIMIT,` LIMIT ${M}`):`${I} LIMIT ${M}`;return q(R,J,k,H)},offset(M){if(!Number.isInteger(M)||M<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${M}`);let H=ye.OFFSET.test(I)?I.replace(ye.OFFSET,` OFFSET ${M}`):`${I} OFFSET ${M}`;return q(R,J,k,H)},toSQL(){return xe(_(),W)},async execute(){return ne(_(),"select")},async executeTakeFirst(){let M=await ne(_(),"select");return Array.isArray(M)?M[0]:M},async executeTakeFirstOrThrow(){let M=await ne(_(),"select"),H=Array.isArray(M)?M[0]:M;if(!H)throw Error("Record not found");return H},async get(){return ne(_(),"select")},async first(){let M=await ne(_(),"select");return Array.isArray(M)?M[0]:M},async firstOrFail(){let M=await ne(_(),"select"),H=Array.isArray(M)?M[0]:M;if(!H)throw Error("No rows found");return H},async count(){let M=k.length>0?N(`SELECT COUNT(*) as c FROM (${W}) as sub`,k):N(`SELECT COUNT(*) as c FROM (${W}) as sub`),H=await ne(M,"select");return Number(H?.[0]?.c??0)},async exists(){let M=k.length>0?N(`SELECT EXISTS(${W}) as e`,k):N(`SELECT EXISTS(${W}) as e`),H=await ne(M,"select");return Boolean(H?.[0]?.e)},async doesntExist(){return!await ee.exists()},values(){return _().values()},raw(){return _().raw()},cancel(){try{_().cancel()}catch{}},whereRaw:d("whereRaw"),whereColumn:d("whereColumn"),orWhereColumn:d("orWhereColumn"),whereIn:d("whereIn"),orWhereIn:d("orWhereIn"),whereNotIn:d("whereNotIn"),orWhereNotIn:d("orWhereNotIn"),whereLike:d("whereLike"),whereILike:d("whereILike"),orWhereLike:d("orWhereLike"),orWhereILike:d("orWhereILike"),whereNotLike:d("whereNotLike"),whereNotILike:d("whereNotILike"),orWhereNotLike:d("orWhereNotLike"),orWhereNotILike:d("orWhereNotILike"),whereAny:d("whereAny"),whereAll:d("whereAll"),whereNone:d("whereNone"),whereNested:d("whereNested"),orWhereNested:d("orWhereNested"),whereDate:d("whereDate"),whereBetween:d("whereBetween"),whereNotBetween:d("whereNotBetween"),whereJsonContains:d("whereJsonContains"),whereJsonPath:d("whereJsonPath"),whereNull:d("whereNull"),orWhereNull:d("orWhereNull"),whereNotNull:d("whereNotNull"),orWhereNotNull:d("orWhereNotNull"),whereExists:d("whereExists"),orWhereExists:d("orWhereExists"),orWhereBetween:d("orWhereBetween"),orWhereRaw:d("orWhereRaw"),whereJsonDoesntContain:d("whereJsonDoesntContain"),whereJsonContainsKey:d("whereJsonContainsKey"),whereJsonDoesntContainKey:d("whereJsonDoesntContainKey"),whereJsonLength:d("whereJsonLength"),join:d("join"),joinSub:d("joinSub"),innerJoin:d("innerJoin"),leftJoin:d("leftJoin"),leftJoinSub:d("leftJoinSub"),rightJoin:d("rightJoin"),crossJoin:d("crossJoin"),crossJoinSub:d("crossJoinSub"),groupBy:d("groupBy"),groupByRaw:d("groupByRaw"),having:d("having"),havingRaw:d("havingRaw"),addSelect:d("addSelect"),select:d("select"),selectAll:d("selectAll"),orderByDesc:d("orderByDesc"),inRandomOrder:d("inRandomOrder"),reorder:d("reorder"),orderByRaw:d("orderByRaw"),union:d("union"),unionAll:d("unionAll"),forPage:d("forPage"),selectAllRelations:d("selectAllRelations"),with:d("with"),value:d("value"),pluck:d("pluck"),cursorPaginate:d("cursorPaginate"),paginate:d("paginate"),simplePaginate:d("simplePaginate"),chunk:d("chunk"),chunkById:d("chunkById"),eachById:d("eachById"),avg:d("avg"),sum:d("sum"),max:d("max"),min:d("min"),find:d("find"),findOrFail:d("findOrFail"),findMany:d("findMany"),latest:d("latest"),oldest:d("oldest"),lazy:d("lazy"),lazyById:d("lazyById"),pipe:(M)=>M(ee),when:d("when"),tap:()=>ee,dump:()=>ee,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>_().simple(),toText:()=>W,toParams:()=>[...k],withTimeout:()=>ee,abort:()=>ee,lockForUpdate:()=>ee,sharedLock:()=>ee,withCTE:()=>ee,withRecursive:()=>ee,cache:()=>ee,clone:()=>ee,withTrashed:()=>ee,onlyTrashed:()=>ee,scope:()=>ee,get rows(){return[]},get row(){return}};return ee}return q(v,[],Y)},insertInto(h){let g,d="",y=[],A=[],f=!1,Y=()=>K?[]:{changes:0,lastInsertRowid:0},v=()=>{let I=async()=>{return},U=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>v(),andWhere:()=>v(),orWhere:()=>v(),orderBy:()=>v(),limit:()=>v(),offset:()=>v(),toSQL:()=>xe(null,""),execute:async()=>[],get:async()=>[],first:I,executeTakeFirst:I,firstOrFail:U,executeTakeFirstOrThrow:U}},K=e.dialect==="postgres",q=(I)=>{let W=I.flat(2).map(String).filter(Boolean),_=W.length>0&&!W.includes("*")?W.map((ee)=>R(ee)).join(", "):"*",G=async()=>{let ee=await ne(N(d,y),"insert"),M=Number(ee?.lastInsertRowid??0),H=Math.max(1,Number(ee?.affectedRows??1)),te=A.filter((me)=>me!==void 0&&me!==null),Z=M>0?N(`SELECT ${_} FROM ${R(String(h))} WHERE ${R("id")} >= ? AND ${R("id")} < ? ORDER BY ${R("id")} ASC`,[M,M+H]):te.length>0?N(`SELECT ${_} FROM ${R(String(h))} WHERE ${R("id")} IN (${te.map(()=>"?").join(", ")}) ORDER BY ${R("id")} ASC`,te):null;if(!Z)return[];let ce=await Z.execute();return Array.isArray(ce)?ce:[]},V=async()=>(await G())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>xe(N(d,y),d),execute:G,get:G,first:V,executeTakeFirst:V,async firstOrFail(){let ee=await V();if(!ee)throw Error("Insert with RETURNING returned no rows");return ee},async executeTakeFirstOrThrow(){let ee=await V();if(!ee)throw Error("Insert with RETURNING returned no rows");return ee}}},R=K?(I)=>`"${String(I).replace(/"/g,'""')}"`:n(e.dialect)?(I)=>`\`${String(I).replace(/`/g,"``")}\``:(I)=>`"${String(I).replace(/"/g,'""')}"`,J=K?"postgres":n(e.dialect)?"mysql":"sqlite",k=K?(I)=>`$${I+1}`:(I)=>"?";return{values(I){let U=Ee(String(h),Array.isArray(I)?I:[I]),W=U.length;if(A=U.map((Z)=>Z?.id),W===0)return f=!0,g=null,d="",y.length=0,this;f=!1;let _=U[0],G=Object.keys(_),V=G.length,ee=W*V;y.length=ee;let M=W===1&&V>0&&typeof h==="string",H=M?oe?.get(h):void 0,te=H?.quoteStyle===J&&H.columns.length===V;if(te){for(let Z=0;Z<V;Z++)if(H.columns[Z]!==G[Z]){te=!1;break}}if(te){d=H.sql;for(let Z=0;Z<V;Z++)y[Z]=_[G[Z]]}else if(W===1)if(!K){let Z=R(G[0]),ce="?";y[0]=_[G[0]];for(let me=1;me<V;me++)Z+=`,${R(G[me])}`,ce+=",?",y[me]=_[G[me]];d=`INSERT INTO ${R(h)}(${Z})VALUES(${ce})`}else{let Z=G.map((ce)=>R(ce)).join(",");d=`INSERT INTO ${R(h)}(${Z})VALUES(`;for(let ce=0;ce<V;ce++){if(ce>0)d+=",";d+=k(ce),y[ce]=_[G[ce]]}d+=")"}else{let Z=G.map((me)=>R(me)).join(",");d=`INSERT INTO ${R(h)}(${Z})VALUES`;let ce=0;for(let me=0;me<W;me++){let Ie=U[me];if(me===0)d+="(";else d+="),(";for(let Le=0;Le<V;Le++){if(Le>0)d+=",";d+=k(ce),y[ce++]=Ie[G[Le]]}}d+=")"}if(M&&!te&&d.length<=8192){if(oe??=new Map,oe.size>=32&&!oe.has(h)){let Z=oe.keys().next().value;if(Z!==void 0)oe.delete(Z)}oe.set(h,{columns:G,quoteStyle:J,sql:d})}if(!B._prepareStatement)g=N(d,y);return this},returning(...I){if(f)return v();if(n(e.dialect))return q(I);let U=`${d} RETURNING ${I.join(", ")}`,W=N(U,y),_=async()=>{let G=await ne(W,"insert");return Array.isArray(G)?G[0]:G};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>xe(W,U),execute:()=>ne(W,"insert"),get:()=>ne(W,"insert"),first:_,executeTakeFirst:_,async firstOrFail(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G},async executeTakeFirstOrThrow(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G}}},toSQL(){if(f)return xe(null,"");if(!g)g=N(d,y);return xe(g,d)},execute(){if(f)return Promise.resolve(Y());let I=be();if(!(I&&(I.onQueryStart||I.onQueryEnd||I.onQueryError||I.startSpan||I.beforeCreate||I.afterCreate||ut(I)))){let W=B._prepareStatement;if(W){let _=W(d);return y.length>0?_.run(...y):_.run()}}if(!g)g=N(d,y);return ne(g,"insert")},async executeTakeFirst(){if(f)return Y();if(!g)g=N(d,y);return await ne(g,"insert")},async executeTakeFirstOrThrow(){if(f)throw Error("Insert failed");if(!g)g=N(d,y);let I=await ne(g,"insert");if(!I)throw Error("Insert failed");return I},returningAll(){return this.returning("*")}}},updateTable(h){let g,d=[],y=(v)=>{let K=String(v);if(n(e.dialect))return`\`${K.replace(/`/g,"``")}\``;return`"${K.replace(/"/g,'""')}"`},A=`UPDATE ${y(String(h))}`,f=!1,Y=(v)=>{A=`${A} ${f?"AND":"WHERE"} ${v}`,f=!0};return{set(v){let K=Ee(String(h),[v])[0],q=Object.keys(K),R=q.length,J=Array.from({length:R});for(let k=0;k<R;k++){let I=q[k],U=K[I];if(it(U))lt(`set(${I})`);if(Fe(U))J[k]=`${y(I)} = ${U.raw}`;else if(Ge(U)){let W=Ye(U,d.length+1);J[k]=`${y(I)} = ${W.text}`,d.push(...W.parameters)}else J[k]=`${y(I)} = ${t(d.length+1)}`,d.push(U)}return A=`${A} SET ${J.join(", ")}`,g=N(A,d),this},where(v,K,q){if(K!==void 0&&(typeof v==="string"||Fe(v)||Ge(v))){let R=$e(K,"updateTable.where"),J;if(typeof v==="string")J=y(v);else if(Fe(v))J=v.raw;else{let U=Ye(v,d.length+1);J=U.text,d.push(...U.parameters)}if(R.toLowerCase()==="in"||R.toLowerCase()==="not in"){let U=Array.isArray(q)?q:[q],W=s(U.length,d.length+1);return Y(`${J} ${R.toUpperCase()} (${W})`),d.push(...U),g=N(A,d),this}let k=Ue(J,R,q,"updateTable.where");if(k)return Y(k),g=N(A,d),this;let I=d.length+1;return Y(`${J} ${R} ${t(I)}`),d.push(q),g=N(A,d),this}if(Array.isArray(v)){let[R,J,k]=v,I=$e(J,"updateTable.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(k)?k:[k],G=s(_.length,d.length+1);return Y(`${y(String(R))} ${I.toUpperCase()} (${G})`),d.push(..._),g=N(A,d),this}let U=Ue(y(String(R)),I,k,"updateTable.where");if(U)return Y(U),g=N(A,d),this;let W=d.length+1;return Y(`${y(String(R))} ${I} ${t(W)}`),d.push(k),g=N(A,d),this}if(it(v))lt("updateTable.where(expr)");if(Fe(v))return Y(v.raw),g=N(A,d),this;if(Ge(v)){let R=Ye(v,d.length+1);return Y(R.text),d.push(...R.parameters),g=N(A,d),this}if(v&&typeof v==="object"){let R=Object.keys(v);if(R.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let J=R.map((k)=>pt(y(k),v[k],d));return Y(J.join(" AND ")),g=N(A,d),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${v===null?"null":typeof v}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(v){return Y(`${y(String(v))} IS NULL`),g=N(A,d),this},whereNotNull(v){return Y(`${y(String(v))} IS NOT NULL`),g=N(A,d),this},returning(...v){let K=this,q=()=>`${A} RETURNING ${v.join(", ")}`,R=()=>d.length>0?N(q(),d):N(q()),J=async()=>{let _=/\sWHERE\s/i.test(A),G=_?A.slice(A.search(/\sWHERE\s/i)+1):"",V=d.slice(d.length-(G.match(/\?|\$\d+/g)?.length??0)),ee=y("id"),M=await(V.length>0?N(`SELECT ${ee} FROM ${y(String(h))}${_?` ${G}`:""}`,V):N(`SELECT ${ee} FROM ${y(String(h))}${_?` ${G}`:""}`)).execute().catch(()=>[]),H=(Array.isArray(M)?M:[]).map((ce)=>ce?.id).filter((ce)=>ce!==void 0&&ce!==null);if(await ne(d.length>0?N(A,d):N(A),"update"),H.length===0)return[];let te=`SELECT ${v.join(", ")} FROM ${y(String(h))} WHERE ${ee} IN (${H.map(()=>"?").join(", ")})`,Z=await N(te,H).execute();return Array.isArray(Z)?Z:[]},k=()=>n(e.dialect)?J():ne(R(),"update"),I=async()=>{let _=await k();return Array.isArray(_)?_[0]:_},U=(_)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${_}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},W={where:(..._)=>(K.where(..._),W),andWhere:(..._)=>(K.where(..._),W),whereNull:(..._)=>(K.whereNull(..._),W),whereNotNull:(..._)=>(K.whereNotNull(..._),W),orWhere:U("orWhere"),orderBy:U("orderBy"),limit:U("limit"),offset:U("offset"),toSQL:()=>xe(R(),q()),execute:k,get:k,first:I,executeTakeFirst:I,async firstOrFail(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _},async executeTakeFirstOrThrow(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _}};return W},toSQL(){if(!g)g=d.length>0?N(A,d):N(A);return xe(g,A)},async execute(){let v=await ne(g,"update");return Qe(v)},async executeTakeFirst(){return{numUpdatedRows:Qe(await ne(g,"update"))}},async executeTakeFirstOrThrow(){let v=Qe(await ne(g,"update"));if(v===0)throw Error("No rows updated");return{numUpdatedRows:v}},returningAll(){return this.returning("*")}}},deleteFrom(h){let g=(R)=>{let J=String(R);if(n(e.dialect))return`\`${J.replace(/`/g,"``")}\``;return`"${J.replace(/"/g,'""')}"`},y=`DELETE FROM ${g(String(h))}`,A=null,f=[],Y=null,v=!1,K=(R)=>{y+=` ${v?"AND":"WHERE"} ${R}`,v=!0},q=()=>{if(A===null)A=f.length>0?N(y,f):N(y);return A};return{where(R,J,k){if(Y=R,typeof R==="string"&&J!==void 0){let I=$e(J,"deleteFrom.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(k)?k:[k],G=s(_.length,f.length+1);return K(`${g(R)} ${I.toUpperCase()} (${G})`),f.push(..._),A=null,this}let U=Ue(g(R),I,k,"deleteFrom.where");if(U)return K(U),A=null,this;let W=f.length+1;return K(`${g(R)} ${I} ${t(W)}`),f.push(k),A=null,this}if(Array.isArray(R)){let[I,U,W]=R,_=$e(U,"deleteFrom.where");if(_.toLowerCase()==="in"||_.toLowerCase()==="not in"){let ee=Array.isArray(W)?W:[W],M=s(ee.length,f.length+1);return K(`${g(String(I))} ${_.toUpperCase()} (${M})`),f.push(...ee),A=null,this}let G=Ue(g(String(I)),_,W,"deleteFrom.where");if(G)return K(G),A=null,this;let V=f.length+1;return K(`${g(String(I))} ${_} ${t(V)}`),f.push(W),A=null,this}if(it(R))lt("deleteFrom.where(expr)");if(Fe(R))return K(R.raw),A=null,this;if(Ge(R)){let I=Ye(R,f.length+1);return K(I.text),f.push(...I.parameters),A=null,this}if(R&&typeof R==="object"){let I=Object.keys(R);if(I.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let U=I.map((W)=>pt(g(W),R[W],f));return K(U.join(" AND ")),A=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${R===null?"null":typeof R}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(R){return K(`${g(String(R))} IS NULL`),A=null,this},whereNotNull(R){return K(`${g(String(R))} IS NOT NULL`),A=null,this},returning(...R){let J=this,k=()=>`${y} RETURNING ${R.join(", ")}`,I=()=>f.length>0?N(k(),f):N(k()),U=async()=>{await be()?.beforeDelete?.({table:String(h),where:Y});let V=n(e.dialect)?await(async()=>{let ee=y.slice(y.search(/\sFROM\s/i)+1),M=`SELECT ${R.join(", ")} ${ee}`,H=await(f.length>0?N(M,f):N(M)).execute();return await ne(f.length>0?N(y,f):N(y),"delete"),Array.isArray(H)?H:[]})():await ne(I(),"delete");try{await be()?.afterDelete?.({table:String(h),where:Y,result:V})}catch{}return V},W=async()=>{let V=await U();return Array.isArray(V)?V[0]:V},_=(V)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${V}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},G={where:(...V)=>(J.where(...V),G),andWhere:(...V)=>(J.where(...V),G),whereNull:(...V)=>(J.whereNull(...V),G),whereNotNull:(...V)=>(J.whereNotNull(...V),G),orWhere:_("orWhere"),orderBy:_("orderBy"),limit:_("limit"),offset:_("offset"),toSQL:()=>xe(I(),k()),execute:()=>U(),get:()=>U(),first:W,executeTakeFirst:W,async firstOrFail(){let V=await W();if(!V)throw Error("Delete with RETURNING returned no rows");return V},async executeTakeFirstOrThrow(){let V=await W();if(!V)throw Error("Delete with RETURNING returned no rows");return V}};return G},toSQL(){return xe(q(),y)},async execute(){try{await be()?.beforeDelete?.({table:String(h),where:Y})}catch(J){throw J}let R=Qe(await ne(q(),"delete"));try{await be()?.afterDelete?.({table:String(h),where:Y,result:R})}catch{}return R},async executeTakeFirst(){return{numDeletedRows:Qe(await ne(q(),"delete"))}},async executeTakeFirstOrThrow(){let R=Qe(await ne(q(),"delete"));if(R===0)throw Error("No rows deleted");return{numDeletedRows:R}},returningAll(){return this.returning("*")}}},table(h){let g=this;return{insert(d){return g.insertInto(h).values(d)},update(d){return g.updateTable(h).set(d)},delete(){return g.deleteFrom(h)},select(...d){if(d.length===0)return g.selectFrom(h);return g.select(h,...d)}}},sql:B,raw(h,...g){if(typeof h==="string")return Wt(h,g);return B(h,...g)},simple(h,...g){return B(h,...g).simple()},async advisoryLock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_lock($1)",[g]);await ne(d,"raw");return}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, -1) AS ok",[g]);await ne(d,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_try_advisory_lock($1) as ok",[g]),y=await ne(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, 0) AS ok",[g]),y=await ne(d,"raw");return Number(y?.[0]?.ok)===1}return!1},async advisoryUnlock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_unlock($1) as ok",[g]),y=await ne(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT RELEASE_LOCK(?) AS ok",[g]),y=await ne(d,"raw");return Number(y?.[0]?.ok)===1}return!1},unsafe(h,g){return Jt(h,g),B.unsafe(h,g)},deferInsert:B.deferInsert?.bind(B),flushDeferredInserts:B.flushDeferredInserts?.bind(B),file(h,g){return B.file(h,g)},async reserve(){let h=await r.reserve(),g=i({sql:h,meta:w,schema:j,hooks:p?.hooks});return g.release=()=>h.release(),g},async close(h){await r.close(h)},async listen(h,g){},async unlisten(h){},async notify(h,g){},async copyTo(h,g){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(h,g,d){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let h=N("SELECT 1");return await ne(h,"select"),!0}catch{return!1}},async waitForReady(h){let g=Math.max(1,h?.attempts??10),d=Math.max(10,h?.delayMs??100);for(let y=0;y<g;y++){if(await this.ping())return;await new Promise((A)=>setTimeout(A,d))}throw Error("Database not ready after waiting")},async transaction(h,g){let y={...p?.txDefaults,...g},A=p?.sql??r,f=p?.inTransaction===!0,Y=f&&typeof A?.savepoint==="function"?"savepoint":"begin",v=async(J)=>{y.logger?.({type:"start",attempt:J});let k=Date.now();return await A[Y](async(I)=>{let U=i({sql:I,meta:w,schema:j,hooks:p?.hooks,inTransaction:!0});if(y?.isolation&&!f){let G=y.isolation,V=G==="read committed"?"READ COMMITTED":G==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(e.dialect==="postgres")await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(n(e.dialect))await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(G!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${G}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(y?.readOnly)if(e.dialect==="postgres")await I.unsafe("SET TRANSACTION READ ONLY");else if(n(e.dialect))await I.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let W=await h(U),_=Date.now()-k;return y.logger?.({type:"commit",attempt:J,durationMs:_}),W})},K=Math.max(0,y?.retries??0),q=0,R;for(;;)try{R=await v(q+1);break}catch(J){let k=Vt(J)||Gt(J,y.sqlStates);if(q<K&&k){q++,y?.onRetry?.(q,J);let I=rn(q,y.backoff);if(I>0)await Yt(I);continue}try{y.onRollback?.(J)}catch{}try{y.afterRollback?.()}catch{}throw J}return await y.afterCommit?.(),R},async savepoint(h){if(p?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let g=B;if(!g||typeof g.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await g.savepoint(async(d)=>{let y=i({sql:d,meta:w,schema:j,hooks:p?.hooks,inTransaction:!0});return await h(y)})},async beginDistributed(h,g){return await(p?.sql??r).beginDistributed(h,async(A)=>{let f=i({sql:A,meta:w,schema:j,hooks:p?.hooks});return await g(f)})},async commitDistributed(h){await r.commitDistributed(h)},async rollbackDistributed(h){await r.rollbackDistributed(h)},setTransactionDefaults(h){p={...p,txDefaults:{...p?.txDefaults,...h}}},transactional(h,g){return(...d)=>this.transaction((y)=>h(y,...d),g)},async insertOrIgnore(h,g){let d=Array.isArray(g)?g:[g];if(!d.length)return;let{colsSql:y,valuesSql:A,params:f}=ft(d),Y=De(String(h)),v=n(e.dialect)?`INSERT IGNORE INTO ${Y} (${y}) VALUES ${A}`:`INSERT INTO ${Y} (${y}) VALUES ${A} ON CONFLICT DO NOTHING`;return N(v,f).execute()},async insertGetId(h,g,d="id"){let{colsSql:y,valuesSql:A,params:f}=ft([g]),Y=De(String(h));if(n(e.dialect)){await N(`INSERT INTO ${Y} (${y}) VALUES ${A}`,f).execute();let[K]=await N("SELECT LAST_INSERT_ID() as id").execute();return K?.id}if(e.dialect==="sqlite"){let K=await N(`INSERT INTO ${Y} (${y}) VALUES ${A}`,f).execute();if(K?.lastInsertRowid!=null)return K.lastInsertRowid;let[q]=await N("SELECT last_insert_rowid() as id").execute();return q?.id}let[v]=await N(`INSERT INTO ${Y} (${y}) VALUES ${A} RETURNING ${De(String(d))} as id`,f).execute();return v?.id},async updateOrInsert(h,g,d){let y=De(String(h)),A=Object.keys(g),f=1,Y=A.map((k)=>`${De(k)} = ${t(f++)}`).join(" AND "),v=A.map((k)=>g[k]);if((await N(`SELECT 1 FROM ${y} WHERE ${Y} LIMIT 1`,v).execute()).length){let k=Object.keys(d),I=1,U=k.map((G)=>`${De(G)} = ${t(I++)}`).join(", "),W=A.map((G)=>`${De(G)} = ${t(I++)}`).join(" AND "),_=[...k.map((G)=>d[G]),...A.map((G)=>g[G])];return await N(`UPDATE ${y} SET ${U} WHERE ${W}`,_).execute(),!0}let{colsSql:q,valuesSql:R,params:J}=ft([{...g,...d}]);return await N(`INSERT INTO ${y} (${q}) VALUES ${R}`,J).execute(),!0},async upsert(h,g,d,y){let A=d.map((U)=>String(U)),f=(y??[]).map((U)=>String(U)),Y=g;if(!Y.length)return;let{colsSql:v,valuesSql:K,params:q}=ft(Y),R=De(String(h)),J=`INSERT INTO ${R} (${v}) VALUES ${K}`;if(n(e.dialect)){if(f.length===0)return N(`INSERT IGNORE INTO ${R} (${v}) VALUES ${K}`,q).execute();let U=f.map((W)=>`${De(W)} = VALUES(${De(W)})`).join(", ");return N(`${J} ON DUPLICATE KEY UPDATE ${U}`,q).execute()}let k=A.map(De).join(", ");if(f.length===0)return N(`${J} ON CONFLICT (${k}) DO NOTHING`,q).execute();let I=f.map((U)=>`${De(U)} = EXCLUDED.${De(U)}`).join(", ");return N(`${J} ON CONFLICT (${k}) DO UPDATE SET ${I}`,q).execute()},async save(h,g){let d=w?.primaryKeys[String(h)]??"id",y=g[d];if(y!=null)if(await this.selectFrom(h).find(y)){await this.updateTable(h).set(g).where({[d]:y}).execute();let f=await this.selectFrom(h).find(y);if(!f)throw Error("save() failed to retrieve updated row");return f}else return await this.create(h,g);return await this.create(h,g)},async remove(h,g){return await this.deleteFrom(h).where({id:g}).execute()},async find(h,g){return await this.selectFrom(h).find(g)},async findOrFail(h,g){return await this.selectFrom(h).findOrFail(g)},async findMany(h,g){return await this.selectFrom(h).findMany(g)},async latest(h,g){return await this.selectFrom(h).latest(g).first()},async oldest(h,g){return await this.selectFrom(h).oldest(g).first()},skip(h,g){return this.selectFrom(h).offset(g)},async rawQuery(h){let g=Date.now();try{be()?.onQueryStart?.({sql:h,kind:"raw"});let d=await B.unsafe(h);return be()?.onQueryEnd?.({sql:h,durationMs:Date.now()-g,kind:"raw"}),d}catch(d){throw be()?.onQueryError?.({sql:h,error:d,durationMs:Date.now()-g,kind:"raw"}),d}},async create(h,g){let d=w?.primaryKeys[String(h)]??"id";try{await be()?.beforeCreate?.({table:String(h),data:g})}catch(y){throw y}if(e.dialect==="postgres"){let y=B`INSERT INTO ${B(String(h))} ${B(g)} RETURNING ${B(String(d))} as id`,[A]=await y.execute();if(!A?.id)throw console.error(`create() failed to get insert ID for table ${String(h)}`),console.error("Inserted values:",g),Error(`create() failed to get insert ID for table ${String(h)}`);let f=await this.selectFrom(h).find(A.id);if(!f)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`);try{await be()?.afterCreate?.({table:String(h),data:g,result:f})}catch{}return f}else{let y=await this.insertGetId(h,g,d);if(y==null)throw Error(`create() failed to get insert ID for table ${String(h)}`);let A=await this.selectFrom(h).find(y);if(!A)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`);try{await be()?.afterCreate?.({table:String(h),data:g,result:A})}catch{}return A}},async createMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,Y=Array.from({length:f*A}),v=n(e.dialect)?(R)=>`\`${String(R).replace(/`/g,"``")}\``:(R)=>`"${String(R).replace(/"/g,'""')}"`,K=`INSERT INTO ${v(String(h))}(${y.map(v).join(",")})VALUES`,q=0;for(let R=0;R<f;R++){if(R>0)K+=",";K+="(";let J=g[R];for(let k=0;k<A;k++){if(k>0)K+=",";K+=t(q+1),Y[q++]=J[y[k]]}K+=")"}return N(K,Y).execute()},async insertMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,Y=f*A,v=Array(Y),K=e.dialect==="postgres",q;if(!K){let k=Array(A);for(let I=0;I<A;I++)k[I]="?";q=`(${k.join(",")})`}else q="";let R=Array(f+2);R[0]=`INSERT INTO ${h}(${y.join(",")})VALUES`;let J=0;if(!K){for(let k=0;k<f;k++){let I=g[k];R[k+1]=q;for(let U=0;U<A;U++)v[J++]=I[y[U]]}return N(R[0]+R.slice(1,f+1).join(","),v).execute()}for(let k=0;k<f;k++){let I=g[k],U=Array(A);for(let W=0;W<A;W++)U[W]=`$${J+1}`,v[J++]=I[y[W]];R[k+1]=`(${U.join(",")})`}return N(R[0]+R.slice(1,f+1).join(","),v).execute()},async updateMany(h,g,d){let y=Object.keys(d),A=y.length;if(A===0)return 0;let f=[],Y=Array.from({length:A});for(let K=0;K<A;K++)Y[K]=`${y[K]}=${t(K+1)}`,f.push(d[y[K]]);let v=`UPDATE ${h} SET ${Y.join(",")}`;if(Array.isArray(g)){let K=$e(String(g[1]),"updateMany");v+=` WHERE ${g[0]} ${K} ${t(f.length+1)}`,f.push(g[2])}else if(Fe(g))v+=` WHERE ${g.raw}`;else if(Ge(g)){let K=Ye(g,f.length+1);v+=` WHERE ${K.text}`,f.push(...K.parameters)}else if(g&&typeof g==="object"&&Object.keys(g).length>0){let K=Object.keys(g).map((q)=>pt(q,g[q],f));v+=` WHERE ${K.join(" AND ")}`}else if(g&&typeof g==="object")throw TypeError("[query-builder] updateMany(): an empty object is not a filter. Pass a condition, or use updateTable(table).set(data).execute() if updating every row is intended.");else throw TypeError(`[query-builder] updateMany(): expected a condition, got ${g===null?"null":typeof g}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return N(v,f).execute()},async deleteMany(h,g){if(!Array.isArray(g)||g.length===0)return 0;let d=w?.primaryKeys[String(h)]??"id",y=g.length;if(e.dialect==="postgres"){let f=Array(y);for(let Y=0;Y<y;Y++)f[Y]=`$${Y+1}`;return N(`DELETE FROM ${h} WHERE ${d} IN (${f.join(",")})`,g).execute()}let A=Array(y);for(let f=0;f<y;f++)A[f]="?";return N(`DELETE FROM ${h} WHERE ${d} IN (${A.join(",")})`,g).execute()},async firstOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y)return y;return await this.create(h,{...g,...d})},async updateOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y){await this.updateTable(h).set(d).where(g).execute();let A=w?.primaryKeys[String(h)]??"id",f=y[A],Y=f!=null?await this.selectFrom(h).find(f):await this.selectFrom(h).where(g).first();if(!Y)throw Error("updateOrCreate() failed to retrieve updated row");return Y}return await this.create(h,{...g,...d})},async count(h,g){let d=g?B(String(g)):B`*`,y=B`SELECT COUNT(${d}) as c FROM ${B(String(h))}`,[A]=await y.execute();return Number(A?.c??0)},async sum(h,g){let d=B`SELECT SUM(${B(String(g))}) as s FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.s??0)},async avg(h,g){let d=B`SELECT AVG(${B(String(g))}) as a FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.a??0)},async min(h,g){let d=B`SELECT MIN(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},async max(h,g){let d=B`SELECT MAX(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},getRelationships(h){if(!w?.relations)return{};let g=w.relations[h];if(!g)return{};let d={};for(let[y,A]of Object.entries(g))if(A&&typeof A==="object"&&Object.keys(A).length>0)d[y]=A;return d},hasRelationship(h,g){if(!w?.relations)return!1;let d=w.relations[h];if(!d)return!1;return Object.values(d).some((y)=>y&&typeof y==="object"&&(g in y))},getRelationshipType(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A)return y;return null},getRelationshipTarget(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A){let f=A[g];if(typeof f==="string")return w.modelToTable[f]||f;else if(f&&typeof f==="object"){if("model"in f)return w.modelToTable[f.model]||f.model;if("target"in f)return w.modelToTable[f.target]||f.target}}return null}}}function Re(){mt.clear()}function Ae(p){mt.setMaxSize(p)}
3
- export{E,In,en,c,Ct,Rt,i,Re,Ae};