bun-query-builder 0.3.5 → 0.3.7

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 +1,3 @@
1
1
  // @bun
2
- import{qe}from"./chunk-xk3qn91x.js";import{n,e,k,_,b,Ke,m,D,l,nt,Y}from"./chunk-455vt4nn.js";import{Database as Te}from"bun:sqlite";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 Oe(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}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 Fe(t){return typeof t==="function"}function We(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[We(s)];if(Fe(a))return a.bind(o);return}})}function At(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 X(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Se=/^[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(!Se.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Pe(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||!Se.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&&Y(t)===0)return[];return r}var ae=null,we=new Map;function Ue(t,r){we.set(t,r),re.clear()}function Mt(){we.clear(),re.clear()}function j(t){if(!ae)try{ae=import.meta.require("./chunk-zkgctd8f.js").getModel}catch{ae=()=>{return}}return ae(t)??we.get(t)}var le=new Map,He=500;function Re(t){let r=le.get(t);if(r!==void 0)return r;let o=nt(t,"postgres");if(le.size>=He)le.clear();return le.set(t,o),o}function Nt(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 Ot(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"?Re(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:Nt(o),lastInsertId:Ot(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Re(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=Ot(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:Nt(s)||1,lastInsertId:i}}}var Q=null,ce=!1,U=null,ne=null,ue=null,de=null;function On(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 Bn(){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 _e=!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&&!_e)_e=!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 Pn(){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,xe=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 Ae(t){return 2**Math.floor(Math.log2(t))}var L="deleted_at",Ee=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 ve=new WeakMap;function Ge(t){let r=ve.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 ve.set(t,o),o}function Ie(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 Ie(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=je(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 Bt(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=Ie(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=X(),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=X();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=X();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 Ne=new Map,Ce=new Map,re=new Map,Je=1000;function W(t){return C(t)}function C(t){let r=Ne.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Ne.set(t,r),r}function G(t){let r=Ce.get(t);if(r!==void 0)return r;return r=Ke(t),Ce.set(t,r),r}var fe=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ze=[...fe,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function $e(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)=>$e(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)=>$e(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 je(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??{},Le=q?.primaryKey??"id";for(let se of Object.keys(he)){if(se===F||se===J||se===Le)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 Bt{_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(Pe(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 X()}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(Pe(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=je(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(X());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?X():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+=Ee){let x=g.slice(M,M+Ee),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(X());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+=xe){let h=T.slice(w,w+xe),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=Ae(Math.max(1,Math.floor(Qe/f.length)));for(let M=0;M<T.length;){let x=Math.min(R,Ae(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 Pt(t){let r=tt(t);if(t?.name)Ue(t.name,r);return r}async function _n(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=Oe(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 In(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=At(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=X();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 Xt(t){return oe.get(t)}function Zt(){return[...oe.values()]}function en(){return Object.fromEntries(oe)}function tn(t){return oe.has(t)}function nn(){oe.clear(),Mt()}function _t(t,r){return oe.set(t,r),r}function rt(){return typeof window<"u"&&typeof document<"u"}function rn(t){let r;if(rt())r=qe(t);else{let o=Pt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return _t(t.name,r),r}function sn(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
3
- export{N,Oe,At,Be,O,Mt,Nt,Ot,On,Bn,Pn,Bt,Pt,_n,In,Xt,Zt,en,tn,nn,_t,rn,sn};
2
+ import{We}from"./chunk-93ny6tvm.js";import{n,e,k,_,b,Fe,m,D,l,at,X}from"./chunk-bpwg9p8b.js";function M(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:[],x=Math.floor(Math.random()*g.length);return g[x]},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 x=[...Array.isArray(f)?f:[]],K=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*x.length));for(let A=x.length-1;A>0;A-=1){let E=Math.floor(Math.random()*(A+1));[x[A],x[E]]=[x[E],x[A]]}return x.slice(0,Math.min(K,x.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let x=g.length-1;x>0;x-=1){let K=Math.floor(Math.random()*(x+1));[g[x],g[K]]=[g[K],g[x]]}return g},maybe:(f,g)=>{let x=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<x?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 x=f[g];if(x&&typeof x==="object")return z(x);return x}})}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-baxpnvev.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 R=typeof h==="string"?h:h?.model||"";if(R&&R.toLowerCase()===r.toLowerCase())return R}return null}if(typeof w==="object"){for(let[h,R]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof R==="string"?R:R?.model||R?.target||h}return null}function d(){let w=t.belongsTo;if(!w)return null;let h=r.toLowerCase(),R=(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=R(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 R(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,R]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:R}}return null}function c(w){let h=t[w];if(!h)return null;let R=r.toLowerCase();if(Array.isArray(h)){for(let p of h){let y=typeof p==="string"?p:String(p?.model??"");if(!y||y.toLowerCase()!==R)continue;let N=typeof p==="object"?p?.morphName:void 0;return{model:y,morphName:String(N??`${C(o)}able`)}}return null}if(typeof h==="object")for(let[p,y]of Object.entries(h)){let N=typeof y==="string"?y:String(y?.model??"");if(p.toLowerCase()!==R&&N.toLowerCase()!==R)continue;let P=typeof y==="object"?y?.morphName:void 0;return{model:N,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),R=C(o)+"_id";return{type:"hasMany",relatedModelName:T,relatedTable:h,foreignKey:R,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||G(f),R=C(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:R,localKey:i}}let g=d();if(g){let w=g.model,h=j(w),R=h?.getTable?.()||G(w),p=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${C(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:R,foreignKey:y,localKey:p}}let x=u();if(x){let w=typeof x.entry==="object",h=w?x.entry.model:x.entry,p=j(h)?.getTable?.()||G(h),y=w?x.entry:null,N,P;if(y?.table)N=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.`);N=B.getTable?.()||B.getDefinition?.()?.table||G(y.through)}else{let B=ie(s),q=ie(p);N=[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:N,pivotFkParent:F,pivotFkRelated:J,pivotColumns:V,pivotModelName:P,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let K=(w,h)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let R=w[r]??w[Object.keys(w).find((q)=>q.toLowerCase()===r.toLowerCase())??""];if(!R||typeof R!=="object")return null;let{through:p,target:y}=R;if(!p||!y)return null;let N=j(p),P=N?.getDefinition?.()||N?.definition,F=N?.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`}},A=K(t.hasManyThrough,"hasManyThrough");if(A)return A;let E=K(t.hasOneThrough,"hasOneThrough");if(E)return E;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((x)=>u[x]);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 v{_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 v(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),x=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let K=new Map;for(let A of f){let E=A[a.foreignKey];if(!K.has(E))K.set(E,[]);K.get(E).push(A)}for(let A of r){let E=K.get(A.get(s))||[];A.setRelation(t,E.map((w)=>new I(x,w,!0)))}}else{let K=new Map;for(let A of f){let E=A[a.foreignKey];if(!K.has(E))K.set(E,A)}for(let A of r){let E=K.get(A.get(s));A.setRelation(t,E?new I(x,E,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let A of r){let E=A._attributes[a.foreignKey];if(E!=null)u.add(E)}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),x=g?.getDefinition?.()||g?.definition||this._definition,K=new Map;for(let A of f)K.set(A[a.localKey],A);for(let A of r){let E=A._attributes[a.foreignKey],w=K.get(E);A.setRelation(t,w?new I(x,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],x=j(a.relatedModelName),K=x?.getDefinition?.()||x?.definition||this._definition,A=K?.primaryKey||"id",E=[];if(g.length>0){let p=g.map(()=>"?").join(", ");E=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${A} IN (${p})`,g)}let w=new Map;for(let p of E)w.set(p[A],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 R=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(K,J,!0),B={};for(let[q,he]of Object.entries(F))if(!R.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 R of r)R.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let R of f)g.set(R[c],R[a.throughForeignKey]);let x=[...new Set(f.map((R)=>R[c]))],K=x.map(()=>"?").join(", "),A=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${K})`,x),E=j(a.relatedModelName),w=E?.getDefinition?.()||E?.definition||this._definition,h=new Map;for(let R of A){let p=g.get(R[a.targetForeignKey]);if(p==null)continue;if(!h.has(p))h.set(p,[]);h.get(p).push(new I(w,R,!0))}for(let R of r){let p=h.get(R.get(s))||[];R.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 v(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((K)=>new I(this._definition,K,!0)),g=f.map((K)=>K._attributes[c]);if(g.some((K)=>K==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let K of f)await s.beforeDelete?.(K);let x=0;for(let K=0;K<g.length;K+=Ae){let A=g.slice(K,K+Ae),E=`${c} IN (${A.map(()=>"?").join(", ")})`;x+=t?(await r.run(`UPDATE ${o} SET ${L} = ? WHERE ${E}`,[u,...A])).changes:(await r.run(`DELETE FROM ${o} WHERE ${E}`,A)).changes}for(let K of f){if(t)K._attributes[L]=u;await s.afterDelete?.(K)}return x}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 v(t),where(o,s,i){return new v(t).where(o,s,i)},orWhere(o,s,i){return new v(t).orWhere(o,s,i)},whereIn(o,s){return new v(t).whereIn(o,s)},whereNotIn(o,s){return new v(t).whereNotIn(o,s)},whereNull(o){return new v(t).whereNull(o)},whereNotNull(o){return new v(t).whereNotNull(o)},whereLike(o,s){return new v(t).whereLike(o,s)},orderBy(o,s="asc"){return new v(t).orderBy(o,s)},orderByDesc(o){return new v(t).orderByDesc(o)},select(...o){return new v(t).select(...o)},with(...o){return new v(t).with(...o)},limit:(o)=>new v(t).limit(o),take:(o)=>new v(t).take(o),skip:(o)=>new v(t).skip(o),withTrashed:()=>new v(t).withTrashed(),onlyTrashed:()=>new v(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 v(t).get(),first:()=>new v(t).first(),firstOrFail:()=>new v(t).firstOrFail(),last:()=>new v(t).last(),count:()=>new v(t).count(),exists:()=>new v(t).exists(),doesntExist:()=>new v(t).doesntExist(),paginate:(o,s)=>new v(t).paginate(o,s),whereBetween(o,s){return new v(t).whereBetween(o,s)},whereNotBetween(o,s){return new v(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 K of T){let A=d[K],E=Object.keys(A),w=await i.insert(E.length?`INSERT INTO ${t.table} (${E.join(", ")}) VALUES (${E.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(A),a);await s[K]._markInserted(A,g?w.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&Ve(t,f,T.map((K)=>d[K]))){let K=t.table,A=f.join(", "),E=`INSERT INTO ${K} (${A}) SELECT ${A} FROM jsonb_populate_recordset(NULL::${K}, (?::text)::jsonb)`;for(let w=0;w<T.length;w+=_e){let h=T.slice(w,w+_e),R=JSON.stringify(h.map((N)=>Object.fromEntries(f.map((P)=>[P,d[N][P]??null]))),ze);if(!g){await i.run(E,[R]);for(let N of h)await s[N]._markInserted(d[N]);continue}let p=(await i.all(`${E} RETURNING ${a}`,[R])).map((N)=>N[a]),y=p.every((N)=>typeof N==="number"||typeof N==="bigint")?[...p].sort((N,P)=>N<P?-1:N>P?1:0):p;for(let N=0;N<h.length;N++)await s[h[N]]._markInserted(d[h[N]],y[N])}continue}let x=xe(Math.max(1,Math.floor(Qe/f.length)));for(let K=0;K<T.length;){let A=Math.min(x,xe(T.length-K)),E=T.slice(K,K+A);K+=A;let w=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${E.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=E.flatMap((y)=>f.map((N)=>d[y][N]));if(!g){await i.run(w,h);for(let y of E)await s[y]._markInserted(d[y]);continue}let R=(await i.all(`${w} RETURNING ${a}`,h)).map((y)=>y[a]),p=R.every((y)=>typeof y==="number"||typeof y==="bigint")?[...R].sort((y,N)=>y<N?-1:y>N?1:0):R;for(let y=0;y<E.length;y++)await s[E[y]]._markInserted(d[E[y]],p[y])}}return s},async updateOrCreate(o,s){let i=new v(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 v(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 v(t).orderByDesc(o),oldest:(o="created_at")=>new v(t).orderBy(o,"asc"),max:(o)=>new v(t).max(o),min:(o)=>new v(t).min(o),avg:(o)=>new v(t).avg(o),sum:(o)=>new v(t).sum(o),pluck(o){return new v(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 v(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||M(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{M,Pe,Pt,Be,O,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ht,w,R,Qe,A}from"./chunk-3htakbmy.js";import"./chunk-b5fh1hw4.js";import"./chunk-7dxm19yj.js";import"./chunk-vmptnnff.js";import"./chunk-bpwg9p8b.js";import"./chunk-93ny6tvm.js";export{R as executeMigration,Qe as executeMigrationWithReport,w as generateMigration,A as resetDatabase,ht as saveMigrationSnapshot};
@@ -0,0 +1,21 @@
1
+ import type { ColumnPlan } from '../migrations';
2
+ /**
3
+ * The `(precision, scale)` a decimal column is rendered with.
4
+ *
5
+ * Only one of the two may be declared. A precision on its own keeps the
6
+ * default scale of 2 (clamped to the precision) rather than SQL's implicit 0,
7
+ * because the column is almost always money and silently dropping the cents
8
+ * is the worse surprise. A scale on its own keeps the default precision,
9
+ * widened if the scale would not otherwise fit.
10
+ */
11
+ export declare function decimalPrecision(column: Pick<ColumnPlan, 'precision' | 'scale'>): { precision: number, scale: number };
12
+ /** `decimal(p,s)` for a column, in the spelling every SQL dialect accepts. */
13
+ export declare function decimalTypeSql(column: Pick<ColumnPlan, 'precision' | 'scale'>): string;
14
+ /**
15
+ * The precision a `decimal` column gets when its model does not say.
16
+ *
17
+ * Kept as the long-standing `decimal(10,2)` so a plan or snapshot written
18
+ * before precision was configurable renders, and diffs, exactly as it did.
19
+ */
20
+ export declare const DEFAULT_DECIMAL_PRECISION: 10;
21
+ export declare const DEFAULT_DECIMAL_SCALE: 2;
@@ -8,6 +8,7 @@ import type { ColumnPlan, IndexPlan, RebuildTableSpec, TablePlan } from '../migr
8
8
  export declare const DATE_BUCKET_FORMAT: 'YYYY-MM-DDTHH:MM:SS.000Z';
9
9
  export declare interface DialectDriver {
10
10
  createEnumType: (enumTypeName: string, values: string[]) => string
11
+ addEnumValues?: (enumTypeName: string, values: string[]) => string
11
12
  createTable: (table: TablePlan) => string
12
13
  createIndex: (tableName: string, index: IndexPlan, columns?: readonly ColumnPlan[]) => string
13
14
  addForeignKey: (tableName: string, columnName: string, refTable: string, refColumn: string, onDelete?: string, onUpdate?: string, existingConstraintNames?: string[]) => string
@@ -31,6 +32,7 @@ export declare interface DialectDriver {
31
32
  export type DateBucketGrain = 'hour' | 'day' | 'week' | 'month' | 'year';
32
33
  export declare class PostgresDriver implements DialectDriver {
33
34
  createEnumType(enumTypeName: string, values: string[]): string;
35
+ addEnumValues(enumTypeName: string, values: string[]): string;
34
36
  createTable(table: TablePlan): string;
35
37
  createIndex(tableName: string, index: IndexPlan): string;
36
38
  addForeignKey(tableName: string, columnName: string, refTable: string, refColumn: string, onDelete?: string, onUpdate?: string, existingConstraintNames?: string[]): string;
@@ -18,13 +18,38 @@ export declare function migrationBody(sql: string): string;
18
18
  */
19
19
  export declare function isLosslessTypeChange(from: NormalizedColumnType, to: NormalizedColumnType): boolean;
20
20
  export declare function buildMigrationPlan(models: ModelRecord, options: InferenceOptions): MigrationPlan;
21
- export declare function generateSql(plan: MigrationPlan, opts?: { dryRun?: boolean }): string[];
22
21
  /**
23
- * Helper function to convert SQL statements array to a single string (for backward compatibility)
22
+ * Write rendered migration files into the configured migrations directory.
23
+ *
24
+ * The only place the generator touches the disk. `deterministic` selects the
25
+ * naming scheme: zero-padded sequence numbers for a full-schema corpus (the
26
+ * same models always produce the same file names), timestamps for incremental
27
+ * diffs. A file whose statements the corpus already carries is skipped — see
28
+ * `createMigrationFile`.
29
+ *
30
+ * Returns the names of the files actually written, which is also what
31
+ * {@link lastCreatedMigrationFiles} reports afterwards.
32
+ */
33
+ export declare function writeMigrationFiles(files: GeneratedMigrationFile[], opts: { deterministic: boolean }): string[];
34
+ /**
35
+ * Render the full-schema create migrations for a plan: one file per table,
36
+ * holding its enum types, CREATE TABLE, indexes and (on the last file) any
37
+ * cyclic foreign keys. Pure — nothing is written.
38
+ */
39
+ export declare function generateSqlFiles(plan: MigrationPlan): { statements: string[], files: GeneratedMigrationFile[] };
40
+ /**
41
+ * Render the full-schema SQL for a plan.
42
+ *
43
+ * Pure unless `write: true` is passed, in which case the per-table migration
44
+ * files are also written (see {@link writeMigrationFiles}).
45
+ */
46
+ export declare function generateSql(plan: MigrationPlan, opts?: GenerateSqlOptions): string[];
47
+ /**
48
+ * The full-schema SQL for a plan as one string. Pure: writes nothing.
24
49
  */
25
50
  export declare function generateSqlString(plan: MigrationPlan): string;
26
51
  /**
27
- * Helper function to convert diff SQL statements array to a single string (for backward compatibility)
52
+ * The diff SQL between two plans as one string. Pure: writes nothing.
28
53
  */
29
54
  export declare function generateDiffSqlString(previous: MigrationPlan | undefined, next: MigrationPlan): string;
30
55
  /**
@@ -41,15 +66,44 @@ export declare function hashMigrationPlan(plan: MigrationPlan): string;
41
66
  * SQLite is the lossy one (string/text/date/datetime/json all map to TEXT;
42
67
  * boolean/integer/bigint to INTEGER; float/double/decimal to REAL). For
43
68
  * Postgres/MySQL the normalized type round-trips faithfully enough to compare
44
- * directly.
69
+ * directly — except for the facets the normalized type does not carry, which
70
+ * are spelled out here: a varchar's length on every dialect that has one.
45
71
  */
46
72
  export declare function canonicalStorageType(col: ColumnPlan, dialect: SupportedDialect): string;
73
+ /**
74
+ * Whether a change keeps the physical type but tightens a bound on it, so
75
+ * existing values may no longer fit (a varchar(100) becoming varchar(50), a
76
+ * decimal losing digits, an enum losing a value).
77
+ * Postgres and strict MySQL refuse the ALTER when a row is too long; MySQL in
78
+ * a permissive mode truncates. Either way it is not a free change.
79
+ */
80
+ export declare function isNarrowingChange(from: ColumnPlan, to: ColumnPlan): boolean;
47
81
  /**
48
82
  * Canonical string form of a column default, so equivalent defaults expressed
49
83
  * differently by a live DB vs a model (quoting, casts, `now()` vs
50
84
  * `CURRENT_TIMESTAMP`, `0` vs `'0'`) compare equal.
51
85
  */
52
86
  export declare function canonicalizeDefault(col: ColumnPlan, dialect?: SupportedDialect): string | undefined;
87
+ /**
88
+ * A partial-index predicate reduced to a form that compares equal however it
89
+ * was spelled.
90
+ *
91
+ * The predicate is part of an index's identity: changing `status = 'active'`
92
+ * to `status <> 'archived'` is a different index, and leaving it out of the
93
+ * diff key meant the change emitted nothing at all. But a predicate read back
94
+ * from a live database is not the string the model wrote - Postgres stores
95
+ * `deleted_at IS NULL` as `(deleted_at IS NULL)`, adds `::text` casts to
96
+ * literals, and rewrites `IN (...)` as `= ANY (ARRAY[...])` - and comparing
97
+ * those literally would drop and recreate every partial index on every live
98
+ * reconcile.
99
+ *
100
+ * So, outside string literals (which are kept verbatim): casts, identifier
101
+ * quotes, parentheses, brackets and whitespace are removed, keywords are
102
+ * lowercased, and Postgres's rewrites of IN / NOT IN (to array comparisons)
103
+ * and of a simple BETWEEN (to a pair of comparisons) are mapped back.
104
+ * Two predicates that differ only in those respects are the same index.
105
+ */
106
+ export declare function normalizeIndexPredicate(where: string | undefined): string;
53
107
  /**
54
108
  * Generate comprehensive SQL to migrate from a previous plan to a new plan,
55
109
  * plus a structured list of the operations involved (so callers can gate
@@ -118,6 +172,8 @@ export declare interface ColumnPlan {
118
172
  }
119
173
  enumValues?: string[]
120
174
  maxLength?: number
175
+ precision?: number
176
+ scale?: number
121
177
  enumTypeName?: string
122
178
  }
123
179
  export declare interface IndexPlan {
@@ -166,18 +222,35 @@ export declare interface MigrationOperation {
166
222
  destructive: boolean
167
223
  confidence?: 'high' | 'low'
168
224
  sql: string
225
+ warning?: string
169
226
  }
170
227
  /** Result of {@link generateDiffOperations}: raw statements + structured ops. */
171
228
  export declare interface DiffResult {
172
229
  statements: string[]
173
230
  operations: MigrationOperation[]
231
+ files: GeneratedMigrationFile[]
174
232
  }
175
233
  export declare interface InferenceOptions {
176
234
  dialect: SupportedDialect
177
235
  vitessSharded?: boolean
178
236
  }
237
+ /**
238
+ * One migration file the generator would write: the descriptive part of its
239
+ * name (`create-orders-table`, `alter-orders-table`, ...) and its SQL, without
240
+ * the provenance header or the sequence prefix — both are added only when the
241
+ * file is actually written, by {@link writeMigrationFiles}.
242
+ */
243
+ export declare interface GeneratedMigrationFile {
244
+ name: string
245
+ sql: string
246
+ }
247
+ export declare interface GenerateSqlOptions {
248
+ write?: boolean
249
+ dryRun?: boolean
250
+ }
179
251
  export declare interface DiffOptions {
180
252
  applyRenames?: boolean
253
+ write?: boolean
181
254
  dryRun?: boolean
182
255
  preserveUnknownColumns?: boolean
183
256
  }
@@ -207,4 +280,5 @@ export type MigrationOpKind = | 'create_table'
207
280
  | 'drop_index'
208
281
  | 'add_foreign_key'
209
282
  | 'rebuild_table'
210
- | 'create_enum';
283
+ | 'create_enum'
284
+ | 'add_enum_value';
package/dist/schema.d.ts CHANGED
@@ -55,6 +55,8 @@ export declare interface Attribute {
55
55
  required?: boolean
56
56
  nullable?: boolean
57
57
  type?: string
58
+ precision?: number
59
+ scale?: number
58
60
  default?: string | number | boolean | Date
59
61
  unique?: boolean
60
62
  order?: number
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{fn,mn,hn,p,rt,it,gn,qe,pn,Kn}from"../chunk-xk3qn91x.js";export{rt as BrowserQueryBuilder,p as BrowserQueryError,pn as browserAuth,it as browserQuery,fn as configureBrowser,gn as createBrowserDb,qe as createBrowserModel,Kn as default,mn as getBrowserConfig,hn as isBrowser};
2
+ import{yn,bn,Tn,p,ot,lt,wn,We,Sn,Un}from"../chunk-93ny6tvm.js";export{ot as BrowserQueryBuilder,p as BrowserQueryError,Sn as browserAuth,lt as browserQuery,yn as configureBrowser,wn as createBrowserDb,We as createBrowserModel,Un as default,bn as getBrowserConfig,Tn as isBrowser};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{J,x,kt,Qe,v,Ae,Ge,Je,Me,Ct,f,z,Ne,ze,Rt,Ye,zt,Yt}from"../../chunk-vxh8ktv7.js";export{J as DynamoDBClient,Ne as DynamoDBMigrationDriver,z as DynamoDBMigrationTracker,Ye as EntityQueryBuilder,f as MIGRATIONS_TABLE,Qe as Model,Me as buildDynamoDBMigrationPlan,kt as configureModels,Je as convertSchemaToDefinition,x as createClient,Yt as createDynamo,ze as createMigrationDriver,zt as dynamo,Ge as extractModelSchema,Ae as extractTableDefinition,v as hashTableDefinition,Ct as isDefinitionEqual,Rt as migrateModels};
2
+ import{z,x,Nt,Ye,v,Ne,Xe,Ze,Me,Mt,f,Y,Oe,et,Ot,tt,tn,nn}from"../../chunk-7dxm19yj.js";export{z as DynamoDBClient,Oe as DynamoDBMigrationDriver,Y as DynamoDBMigrationTracker,tt as EntityQueryBuilder,f as MIGRATIONS_TABLE,Ye as Model,Me as buildDynamoDBMigrationPlan,Nt as configureModels,Ze as convertSchemaToDefinition,x as createClient,nn as createDynamo,et as createMigrationDriver,tn as dynamo,Xe as extractModelSchema,Ne as extractTableDefinition,v as hashTableDefinition,Mt as isDefinitionEqual,Ot as migrateModels};
package/dist/src/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{X,Z,ee,te,I,ne,re,ie,se,L,ae,K,F,oe,le,j,ce,ue,st,We,at,C,de,o,fe,me,he,ge,h,ot,w,R,A,pe,ye,q,be,W,Te,U,V,M,H,we,Se,De,Ee,Q,$e,xe,S,g,yn,bn,Tn,lt,ct,ut,dt,ft,wn,mt,Wt,Sn,Dn,En,$n,ht,xn,vn,kn,ve,d,gt,pt,yt,bt,Tt,Ut,G,ke,Cn,Rn,wt,Ue,y,Ve,He,Vt,An,Ht,Mn,St,Dt,Et,Qt,Gt}from"../chunk-pa426cqs.js";import{E,Nn,Jt,c,$t,xt,i,Ce,Re}from"../chunk-r6myba29.js";import{vt,u,J,x,kt,Qe,v,Ae,Ge,Je,Me,Ct,f,z,Ne,ze,Rt,Ye,zt,Yt}from"../chunk-vxh8ktv7.js";import{At,Mt,Nt,Ot,On,Bn,Pn,Bt,Pt,_n,In,Xt,Zt,en,tn,nn,_t,rn,sn}from"../chunk-s66vynk9.js";import{n,Xe,e,B,Ze,t,s,P,Pe,an,et,on,a,_e,It,Lt,ln,Ie,Kt,Ln,Ft,jt,k,_,cn,Ke,T,un,dn,m,nt}from"../chunk-455vt4nn.js";import{fn,mn,hn,p,rt,it,gn,qe,pn}from"../chunk-xk3qn91x.js";export{Bt as BelongsToManyRelationBuilder,rt as BrowserQueryBuilder,p as BrowserQueryError,Ft as DEFAULT_SQLITE_PRAGMAS,J as DynamoDBClient,vt as DynamoDBDriverImpl,g as DynamoDBItemBuilder,Ne as DynamoDBMigrationDriver,z as DynamoDBMigrationTracker,S as DynamoDBQueryBuilder,ht as DynamoDBToolingAdapter,Ye as EntityQueryBuilder,yt as GENERATED_MARKER,a as LibSQLError,f as MIGRATIONS_TABLE,Qe as Model,o as MySQLDriver,fe as PostgresDriver,ge as SQLiteDriver,Ht as Seeder,me as SingleStoreDriver,lt as SingleTableManager,wn as SingleTablePatterns,ut as SingleTableQueryBuilder,ct as SingleTableRepository,y as UTC_CLOCK_DEFAULT,he as VitessDriver,k as applySqliteBootstrapPragmas,Qt as auditSchemaDrift,pn as browserAuth,it as browserQuery,ve as buildDatabaseSchema,Me as buildDynamoDBMigrationPlan,G as buildMigrationPlan,gt as buildSchemaMeta,Z as cacheClear,te as cacheConfig,ee as cacheStats,Ue as canonicalStorageType,Ve as canonicalizeDefault,$e as checkSchema,Mt as clearLocalModels,nn as clearModelRegistry,Ce as clearQueryCache,e as config,fn as configureBrowser,kt as configureModels,On as configureOrm,Je as convertSchemaToDefinition,gn as createBrowserDb,qe as createBrowserModel,x as createClient,Yt as createDynamo,Tn as createDynamoDBClient,u as createDynamoDBDriver,bn as createDynamoDBItemBuilder,yn as createDynamoDBQueryBuilder,xn as createDynamoDBToolingAdapter,At as createFakerCompatLayer,Kt as createLibSQLSQL,ze as createMigrationDriver,Pt as createModel,i as createQueryBuilder,ft as createRepository,dt as createSingleTableManager,_n as createTableFromModel,L as dbInfo,K as dbOptimize,ae as dbStats,F as dbWipe,Lt as decodeLibSQLValue,Xe as defaultConfig,an as defineConfig,rn as defineModel,An as defineModels,Mn as defineSeeder,se as dumpDatabase,zt as dynamo,It as encodeLibSQLValue,xt as escapeStringLiteral,R as executeMigration,oe as explain,U as explainAllQueries,re as exportData,Nt as extractChanges,Ot as extractInsertId,Ge as extractModelSchema,Ae as extractTableDefinition,St as familyOfDeclared,Dt as familyOfSqlType,le as file,Gt as formatSchemaDrift,Se as freshDatabase,vn as generateAccessPatterns,V as generateDiagram,He as generateDiffOperations,Vt as generateDiffSql,Rn as generateDiffSqlString,w as generateMigration,at as generateModelSource,ke as generateSql,Cn as generateSqlString,Zt as getAllModels,mn as getBrowserConfig,P as getConfig,Pn as getDatabase,h as getDialectDriver,Xt as getModel,en as getModelRegistry,t as getPlaceholder,s as getPlaceholders,tn as hasModel,wt as hashMigrationPlan,v as hashTableDefinition,ie as importData,dn as inflectSingular,j as inspectTable,ue as introspect,C as introspectDatabase,hn as isBrowser,Ct as isDefinitionEqual,bt as isGeneratedMigrationSql,Ln as isLibSQLConnection,et as isLibSQLUrl,Ut as isLosslessTypeChange,n as isMysqlLike,Nn as iterateAllPivots,pt as lastCreatedMigrationFiles,d as loadModels,de as makeModel,we as makeSeeder,En as marshallObject,pe as migrateGenerate,be as migrateList,Rt as migrateModels,ye as migrateRollback,q as migrateStatus,Tt as migrationBody,We as modelNameForTable,W as modelShow,Ze as normalizeDialectName,K as optimizeDatabase,Wt as parseStacksModels,Te as ping,U as queryExplainAll,c as quoteColumnForDialect,Jt as raw,sn as registerBrowserModels,_t as registerModel,V as relationDiagram,Bn as releaseOrm,cn as resetConnection,A as resetDatabase,B as resolveDialect,mt as resolveKeyPattern,on as resolveLibSQLEndpoint,_ as resolveLibSQLTarget,E as resolvePivot,jt as resolveSqlitePragmas,X as runBenchmark,H as runSeeder,M as runSeeders,Et as satisfies,ot as saveMigrationSnapshot,In as seedModel,Pe as setConfig,Re as setQueryCacheMaxSize,W as showModel,m as singularizerFor,De as sql,st as sqlTypeToAttr,kn as stacksModelToEntity,I as startConsole,un as stripTrailingS,ce as tableInfo,T as tableNameFor,$t as temporalLiteral,ne as tinker,nt as toDialectPlaceholders,Sn as toDynamoDBItem,Ie as toHranaStatement,_e as toLibSQLError,ln as toLibSQLRows,Dn as toModelInstance,Ke as toTableName,$n as unmarshallItem,Ee as unsafe,Q as validateSchema,xe as waitReady,F as wipeDatabase};
2
+ import{Z,ee,te,ne,I,re,ie,se,ae,L,oe,K,F,le,ce,j,ue,de,ct,Ue,ut,C,fe,o,me,he,ge,pe,h,dt,ft,mt,Ve,He,ht,w,R,Qe,A,ye,be,q,Te,W,we,U,V,N,H,Se,De,Ee,$e,Q,xe,ve,S,g,Dn,En,$n,gt,pt,yt,bt,Tt,xn,wt,Qt,vn,kn,Cn,Rn,St,An,Nn,Mn,ke,d,Dt,Et,$t,xt,vt,Gt,G,J,Ce,Jt,On,Pn,kt,Ge,zt,y,Je,Yt,ze,Xt,Bn,Zt,_n}from"../chunk-3htakbmy.js";import{E,In,en,c,Ct,Rt,i,Re,Ae}from"../chunk-b5fh1hw4.js";import{At,u,z,x,Nt,Ye,v,Ne,Xe,Ze,Me,Mt,f,Y,Oe,et,Ot,tt,tn,nn}from"../chunk-7dxm19yj.js";import{Pt,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un}from"../chunk-vmptnnff.js";import{n,nt,e,P,rt,t,s,B,_e,dn,it,fn,a,Ie,jt,qt,mn,Le,Wt,Wn,Ut,Vt,k,_,hn,Fe,T,gn,pn,m,at}from"../chunk-bpwg9p8b.js";import{yn,bn,Tn,p,ot,lt,wn,We,Sn}from"../chunk-93ny6tvm.js";export{Lt as BelongsToManyRelationBuilder,ot as BrowserQueryBuilder,p as BrowserQueryError,Ut as DEFAULT_SQLITE_PRAGMAS,z as DynamoDBClient,At as DynamoDBDriverImpl,g as DynamoDBItemBuilder,Oe as DynamoDBMigrationDriver,Y as DynamoDBMigrationTracker,S as DynamoDBQueryBuilder,St as DynamoDBToolingAdapter,tt as EntityQueryBuilder,$t as GENERATED_MARKER,a as LibSQLError,f as MIGRATIONS_TABLE,Ye as Model,o as MySQLDriver,me as PostgresDriver,pe as SQLiteDriver,Zt as Seeder,he as SingleStoreDriver,gt as SingleTableManager,xn as SingleTablePatterns,yt as SingleTableQueryBuilder,pt as SingleTableRepository,y as UTC_CLOCK_DEFAULT,ge as VitessDriver,k as applySqliteBootstrapPragmas,Ve as auditSchemaDrift,Sn as browserAuth,lt as browserQuery,ke as buildDatabaseSchema,Me as buildDynamoDBMigrationPlan,G as buildMigrationPlan,Dt as buildSchemaMeta,ee as cacheClear,ne as cacheConfig,te as cacheStats,Ge as canonicalStorageType,Je as canonicalizeDefault,xe as checkSchema,Bt as clearLocalModels,ln as clearModelRegistry,Re as clearQueryCache,e as config,yn as configureBrowser,Nt as configureModels,Ln as configureOrm,Ze as convertSchemaToDefinition,wn as createBrowserDb,We as createBrowserModel,x as createClient,nn as createDynamo,$n as createDynamoDBClient,u as createDynamoDBDriver,En as createDynamoDBItemBuilder,Dn as createDynamoDBQueryBuilder,An as createDynamoDBToolingAdapter,Pt as createFakerCompatLayer,Wt as createLibSQLSQL,et as createMigrationDriver,Kt as createModel,i as createQueryBuilder,Tt as createRepository,bt as createSingleTableManager,jn as createTableFromModel,L as dbInfo,K as dbOptimize,oe as dbStats,F as dbWipe,qt as decodeLibSQLValue,nt as defaultConfig,dn as defineConfig,cn as defineModel,Bn as defineModels,_n as defineSeeder,ae as dumpDatabase,tn as dynamo,jt as encodeLibSQLValue,Rt as escapeStringLiteral,R as executeMigration,Qe as executeMigrationWithReport,le as explain,U as explainAllQueries,ie as exportData,_t as extractChanges,It as extractInsertId,Xe as extractModelSchema,Ne as extractTableDefinition,dt as familyOfDeclared,ft as familyOfSqlType,ce as file,He as formatSchemaDrift,De as freshDatabase,Nn as generateAccessPatterns,V as generateDiagram,ze as generateDiffOperations,Xt as generateDiffSql,Pn as generateDiffSqlString,w as generateMigration,ut as generateModelSource,Jt as generateSql,Ce as generateSqlFiles,On as generateSqlString,sn as getAllModels,bn as getBrowserConfig,B as getConfig,Fn as getDatabase,h as getDialectDriver,rn as getModel,an as getModelRegistry,t as getPlaceholder,s as getPlaceholders,on as hasModel,kt as hashMigrationPlan,v as hashTableDefinition,se as importData,pn as inflectSingular,j as inspectTable,de as introspect,C as introspectDatabase,Tn as isBrowser,Mt as isDefinitionEqual,xt as isGeneratedMigrationSql,Wn as isLibSQLConnection,it as isLibSQLUrl,Gt as isLosslessTypeChange,n as isMysqlLike,zt as isNarrowingChange,In as iterateAllPivots,Et as lastCreatedMigrationFiles,d as loadModels,fe as makeModel,Se as makeSeeder,Cn as marshallObject,ye as migrateGenerate,Te as migrateList,Ot as migrateModels,be as migrateRollback,q as migrateStatus,vt as migrationBody,Ue as modelNameForTable,W as modelShow,rt as normalizeDialectName,Yt as normalizeIndexPredicate,K as optimizeDatabase,Qt as parseStacksModels,we as ping,U as queryExplainAll,c as quoteColumnForDialect,en as raw,un as registerBrowserModels,Ft as registerModel,V as relationDiagram,Kn as releaseOrm,hn as resetConnection,A as resetDatabase,P as resolveDialect,wt as resolveKeyPattern,fn as resolveLibSQLEndpoint,_ as resolveLibSQLTarget,E as resolvePivot,Vt as resolveSqlitePragmas,Z as runBenchmark,H as runSeeder,N as runSeeders,mt as satisfies,ht as saveMigrationSnapshot,qn as seedModel,_e as setConfig,Ae as setQueryCacheMaxSize,W as showModel,m as singularizerFor,Ee as sql,ct as sqlTypeToAttr,Mn as stacksModelToEntity,I as startConsole,gn as stripTrailingS,ue as tableInfo,T as tableNameFor,Ct as temporalLiteral,re as tinker,at as toDialectPlaceholders,vn as toDynamoDBItem,Le as toHranaStatement,Ie as toLibSQLError,mn as toLibSQLRows,kn as toModelInstance,Fe as toTableName,Rn as unmarshallItem,$e as unsafe,Q as validateSchema,ve as waitReady,F as wipeDatabase,J as writeMigrationFiles};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{n,Xe,e,B,Ze,t,s,P,Pe,an,Ft,jt,k,_,cn}from"../chunk-455vt4nn.js";import{Jt,c,$t,xt,i,Ce,Re}from"../chunk-r6myba29.js";export{Ft as DEFAULT_SQLITE_PRAGMAS,k as applySqliteBootstrapPragmas,Ce as clearQueryCache,e as config,i as createQueryBuilder,Xe as defaultConfig,an as defineConfig,xt as escapeStringLiteral,P as getConfig,t as getPlaceholder,s as getPlaceholders,n as isMysqlLike,Ze as normalizeDialectName,c as quoteColumnForDialect,Jt as raw,cn as resetConnection,B as resolveDialect,_ as resolveLibSQLTarget,jt as resolveSqlitePragmas,Pe as setConfig,Re as setQueryCacheMaxSize,$t as temporalLiteral};
2
+ import{n,nt,e,P,rt,t,s,B,_e,dn,Ut,Vt,k,_,hn}from"../chunk-bpwg9p8b.js";import{en,c,Ct,Rt,i,Re,Ae}from"../chunk-b5fh1hw4.js";export{Ut as DEFAULT_SQLITE_PRAGMAS,k as applySqliteBootstrapPragmas,Re as clearQueryCache,e as config,i as createQueryBuilder,nt as defaultConfig,dn as defineConfig,Rt as escapeStringLiteral,B as getConfig,t as getPlaceholder,s as getPlaceholders,n as isMysqlLike,rt as normalizeDialectName,c as quoteColumnForDialect,en as raw,hn as resetConnection,P as resolveDialect,_ as resolveLibSQLTarget,Vt as resolveSqlitePragmas,_e as setConfig,Ae as setQueryCacheMaxSize,Ct as temporalLiteral};
package/dist/types.d.ts CHANGED
@@ -287,6 +287,7 @@ export declare interface GenerateMigrationResult {
287
287
  hasChanges: boolean
288
288
  plan: import('./migrations').MigrationPlan
289
289
  operations?: import('./migrations').MigrationOperation[]
290
+ files?: import('./migrations').GeneratedMigrationFile[]
290
291
  }
291
292
  export declare interface UnsafeOptions {
292
293
  params?: string
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bun-query-builder",
3
3
  "type": "module",
4
- "version": "0.3.5",
4
+ "version": "0.3.7",
5
5
  "description": "A simple yet performant query builder for TypeScript. Built with Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ot,w,R,A}from"./chunk-pa426cqs.js";import"./chunk-r6myba29.js";import"./chunk-vxh8ktv7.js";import"./chunk-s66vynk9.js";import"./chunk-455vt4nn.js";import"./chunk-xk3qn91x.js";export{R as executeMigration,w as generateMigration,A as resetDatabase,ot as saveMigrationSnapshot};