bun-query-builder 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +2 -2
- package/dist/{chunk-6r90xd1j.js → chunk-5eatvs7h.js} +2 -2
- package/dist/chunk-axxs7680.js +3 -0
- package/dist/{chunk-hgsjz3vz.js → chunk-g2ryjpbk.js} +1 -1
- package/dist/{chunk-dvg3pg8k.js → chunk-zbjamkgf.js} +1 -1
- package/dist/orm.d.ts +40 -6
- package/dist/src/index.js +1 -1
- package/dist/type-inference.d.ts +2 -0
- package/package.json +2 -2
- package/dist/chunk-cxpaxq2p.js +0 -3
package/dist/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"../chunk-hjgcemhy.js";import"../chunk-4cs1xx1d.js";import"../chunk-c7m701dd.js";import"../chunk-
|
|
3
|
+
import"../chunk-hjgcemhy.js";import"../chunk-4cs1xx1d.js";import"../chunk-c7m701dd.js";import"../chunk-axxs7680.js";import"../chunk-3xpe6b57.js";import{J,z,Y,X,O,Z,ee,te,ne,_,re,I,L,ie,se,K,ae,oe,k,le,T,C,R,me,he,F,ge,j,pe,q,W,A,U,ye,be,Te,we,V,Se,De}from"../chunk-5eatvs7h.js";import{EventEmitter as Le}from"events";import v from"process";import Ie from"process";import fe from"process";import G from"process";import M from"process";import qe from"tty";import Et,{stdin as Gt,stdout as Ht}from"process";import{existsSync as Bt}from"fs";import ce from"fs/promises";import Me from"os";import ue from"path";import x from"process";function de(e){return e.replace(/[<[].+/,"").trim()}function Ne(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],a=(d)=>{let n=!1,r=d[1];if(r.startsWith("..."))r=r.slice(3),n=!0;else if(r.endsWith("..."))r=r.slice(0,-3),n=!0;return{required:d[0].startsWith("<"),value:r.trim(),variadic:n}},o;while(o=t.exec(e))s.push(a(o));let m;while(m=i.exec(e))s.push(a(m));return s}function Pe(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,m)=>m!==i&&o.names.some((d)=>s.names.includes(d))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function Ee(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function Q(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function P(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function We(e,t,i){let s=0,a=t.length,o=e,m;for(;s<a;++s)m=o[t[s]],o=o[t[s]]=s===a-1?i:m!=null?m:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function Fe(e,t){for(let i of Object.keys(t)){let s=t[i];if(e[i]===void 0)continue;if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function ze(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function B(e){return e.split(".").map((t,i)=>i===0?P(t):t).join(".")}class N extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
|
|
4
4
|
|
|
5
5
|
Stack trace:
|
|
6
6
|
${this.stack}`;return this.message}}function Ue(e){if(e instanceof N)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function Ge(){let{env:e}=Ie,{TERM:t,TERM_PROGRAM:i}=e;if(Ie.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||i==="Terminus-Sublime"||i==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var H="\x1B",b=`${H}[`;var ke={to(e,t){if(!t)return`${b}${e+1}G`;return`${b}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${b}${-e}D`;else if(e>0)i+=`${b}${e}C`;if(t<0)i+=`${b}${-t}A`;else if(t>0)i+=`${b}${t}B`;return i},up:(e=1)=>`${b}${e}A`,down:(e=1)=>`${b}${e}B`,forward:(e=1)=>`${b}${e}C`,backward:(e=1)=>`${b}${e}D`,nextLine:(e=1)=>`${b}E`.repeat(e),prevLine:(e=1)=>`${b}F`.repeat(e),left:`${b}G`,hide:`${b}?25l`,show:`${b}?25h`,save:`${H}7`,restore:`${H}8`};var Vt={screen:`${b}2J`,up:(e=1)=>`${b}1J`.repeat(e),down:(e=1)=>`${b}J`.repeat(e),line:`${b}2K`,lineEnd:`${b}K`,lineStart:`${b}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?ke.up():"");if(e)t+=ke.left;return t}},Lt={screen:`${H}c`};function He(e,t){let i=[];for(let s=0;s<=t.length;s++)i[s]=[s];for(let s=0;s<=e.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let a=1;a<=e.length;a++)if(t.charAt(s-1)===e.charAt(a-1))i[s][a]=i[s-1][a-1];else i[s][a]=Math.min(i[s-1][a-1]+1,i[s][a-1]+1,i[s-1][a]+1);return i[t.length][e.length]}function Be(e,t,i=2,s=3){return t.map((a)=>({cmd:a,distance:He(e,a)})).filter(({distance:a})=>a<=i).sort((a,o)=>a.distance-o.distance).slice(0,s).map(({cmd:a})=>a)}function Ke(e,t={}){let i={_:[]},s=t.alias||{},a=new Set(t.boolean||[]),o={};for(let n of Object.keys(s))for(let r of s[n])o[r]=n;for(let n of a)if(s[n])for(let r of s[n])a.add(r);function m(n,r){if(n===void 0)return r;if(typeof r==="boolean")return r;return Array.isArray(n)?[...n,r]:[n,r]}function d(n,r){let c=o[n]||n,h=m(i[c],r);if(i[c]=h,s[c])for(let l of s[c])i[l]=h;if(o[n]&&s[o[n]])for(let l of s[o[n]])i[l]=h;i[n]=h}for(let n=0;n<e.length;n++){let r=e[n];if(r==="--"){i._.push(...e.slice(n+1));break}if(r.startsWith("--")){let c=r.indexOf("=");if(c!==-1){let h=P(r.slice(2,c)),l=r.slice(c+1);d(h,l)}else{let h=r.slice(2);if(h.startsWith("no-")){let p=P(h.slice(3));d(p,!1);continue}let l=P(h),y=o[l]||l;if(a.has(y)||a.has(l))d(l,!0);else{let p=e[n+1];if(p!==void 0&&!p.startsWith("-"))d(l,p),n++;else d(l,!0)}}}else if(r.startsWith("-")&&r.length>1){let c=r.slice(1);for(let h=0;h<c.length;h++){let l=c[h],y=o[l]||l;if(h===c.length-1&&!a.has(y)&&!a.has(l)){let p=e[n+1];if(p!==void 0&&!p.startsWith("-"))d(l,p),n++;else d(l,!0)}else d(l,!0)}}else i._.push(r)}return i}class je{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(e),this.names=de(e).split(",").map((s)=>{let a=s.trim().replace(/^-{1,2}/,"");if(a.startsWith("no-"))this.negated=!0,a=a.replace(/^no-/,"");return B(a)}).sort((s,a)=>s.length>a.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var Dt=fe.argv,Ye=`${fe.platform}-${fe.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,_e=G.argv,Qe=`${G.platform}-${G.arch} node-${G.version}`;class $e{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,i,s){this.rawName=e,this.description=t,this.config=i,this.cli=s,this.options=[],this.aliasNames=[],this.name=de(e);let a=de(e),o=a.indexOf(":");if(o>0)this.namespace=a.substring(0,o),this.name=a.substring(o+1);if(this.args=Ne(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!i)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,i){let s=new je(e,t,i);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof ve}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=B(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>B(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:a}=this.cli.globalCommand,o=[{body:`${e}${i?`/${i}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let r=Ee(t.map((p)=>p.rawName)),c=new Map,h=[];for(let p of t)if(p.namespace){if(!c.has(p.namespace))c.set(p.namespace,[]);c.get(p.namespace).push(p)}else h.push(p);let l="";if(h.sort((p,D)=>p.rawName<D.rawName?-1:p.rawName>D.rawName?1:0),h.length>0)l+=h.map((p)=>` ${Q(p.rawName,r.length)} ${p.description}`).join(`
|
|
@@ -29,7 +29,7 @@ Received ${i}, cleaning up...`),e)try{await e()}catch(s){console.error("Error du
|
|
|
29
29
|
`)),this.enableDidYouMean){let t=[];for(let s of this.commands){if(s.displayName)t.push(s.displayName);if(s.aliasNames)t.push(...s.aliasNames)}let i=Be(e,t);if(i.length>0)console.log(E.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${E.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(E.dim("Run"),`${this.name} --help`,E.dim("to see all available commands")),v.exit(1)}async parse(e=_e,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(n){throw this.handleUsageError(n),n}if(this.rawArgs=e,!this.name)this.name=e[1]?ze(e[1]):"cli";let a=!0,o=e.slice(2),m=o[0];if(m&&!m.startsWith("-")){for(let n of this.commands)if(n.isMatched(m)){let r=this.mri(o,n);a=!1;let c={...r,args:r.args.slice(1)};this.setParsedInfo(c,n,m),this.emit(`command:${m}`,n);break}if(a){let n=o[1];if(n&&!n.startsWith("-")){let r=`${m}:${n}`;for(let c of this.commands)if(c.isMatched(r)){let h=this.mri(o,c);a=!1;let l={...h,args:h.args.slice(2)};this.setParsedInfo(l,c,r),this.emit(`command:${r}`,c);break}}}}if(a){for(let n of this.commands)if(n.name===""){a=!1;let r=this.mri(o,n);this.setParsedInfo(r,n),this.emit("command:!",n);break}}if(a){let n=this.mri(e.slice(2));this.setParsedInfo(n)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),i=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),i=!1,this.unsetMatchedCommand();let d={args:this.args,options:this.options};if(i)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return d}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=Pe(i),a=[],o=e.indexOf("--");if(o>-1)a=e.slice(o+1),e=e.slice(0,o);let m=Ke(e,s),d={_:m._};for(let l of Object.keys(m))if(l!=="_")d[B(l)]=m[l];let n=d._,r={"--":a},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let l of i){if(!c&&l.config.default!==void 0)for(let y of l.names)r[y]=l.config.default;if(Array.isArray(l.config.type)){if(h[l.name]===void 0)h[l.name]={shouldTransform:!0,transformFunction:l.config.type[0]}}}for(let l of Object.keys(d))if(l!=="_"){let y=l.split(".");We(r,y,d[l]),Fe(r,h)}for(let l of i){if(!l.variadic)continue;for(let y of l.names){let p=r[y];if(p===void 0||Array.isArray(p))continue;if(l.config.default!==void 0&&p===l.config.default)continue;r[y]=[p]}}return{args:n,options:r}}async run(e=_e){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!Ue(e)||e.isUsageError===!1)return;let t=e.message||"command-line error",i=this.name?`${this.name}: `:"",s=/--help/.test(t)?"":e.usage?`
|
|
30
30
|
Usage: ${e.usage}`:`
|
|
31
31
|
Run \`${this.name??"cli"} --help\` for usage.`;v.stderr.write(`${i}${t}${s}
|
|
32
|
-
`),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((d,n)=>{if(d.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let a={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(a);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,n=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...a,next:n})}else await m()};await n()}else await m();for(let d of i.afterHooks)await d(a);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Ae{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Wt=new Ae;function et(){if("FORCE_COLOR"in M.env)return M.env.FORCE_COLOR!=="0";if("NO_COLOR"in M.env||M.env.TERM==="dumb")return!1;if(M.platform==="win32")return!0;return qe.isatty(1)&&qe.isatty(2)}var Re=et();function g(e,t){if(!Re)return(i)=>i;return(i)=>e+i+t}var tt=g("\x1B[0m","\x1B[0m"),it=g("\x1B[31m","\x1B[39m"),st=g("\x1B[32m","\x1B[39m"),rt=g("\x1B[33m","\x1B[39m"),nt=g("\x1B[34m","\x1B[39m"),at=g("\x1B[35m","\x1B[39m"),ot=g("\x1B[36m","\x1B[39m"),lt=g("\x1B[37m","\x1B[39m"),ct=g("\x1B[90m","\x1B[39m"),ut=g("\x1B[1m","\x1B[22m"),dt=g("\x1B[3m","\x1B[23m"),mt=g("\x1B[4m","\x1B[24m"),ht=g("\x1B[2m","\x1B[22m"),pt=g("\x1B[7m","\x1B[27m"),ft=g("\x1B[8m","\x1B[28m"),gt=g("\x1B[9m","\x1B[29m"),bt=g("\x1B[41m","\x1B[49m"),yt=g("\x1B[42m","\x1B[49m"),$t=g("\x1B[43m","\x1B[49m"),vt=g("\x1B[44m","\x1B[49m"),wt=g("\x1B[45m","\x1B[49m"),xt=g("\x1B[46m","\x1B[49m"),Ct=g("\x1B[47m","\x1B[49m"),St=Re,Ot={reset:tt,red:it,green:st,yellow:rt,blue:nt,magenta:at,cyan:ot,white:lt,gray:ct,bold:ut,italic:dt,underline:mt,dim:ht,inverse:pt,hidden:ft,strikethrough:gt,bgRed:bt,bgGreen:yt,bgYellow:$t,bgBlue:vt,bgMagenta:wt,bgCyan:xt,bgWhite:Ct,isColorSupported:St},It=Ot,kt=["up","down","left","right","space","enter","cancel"],Kt={actions:new Set(kt),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var Yt=Et.platform.startsWith("win"),Qt=Symbol("clapp:cancel");var _t=Ge();var f=(e,t)=>_t?e:t,Jt=f("\u25C6","*"),Xt=f("\u25A0","x"),Zt=f("\u25B2","x"),ei=f("\u25C7","o"),ti=f("\u250C","T"),qt=f("\u2502","|"),ii=f("\u2514","\u2014"),si=f("\u25CF",">"),ri=f("\u25CB"," "),ni=f("\u25FB","[\u2022]"),ai=f("\u25FC","[+]"),oi=f("\u25FB","[ ]"),li=f("\u25AA","\u2022"),ci=f("\u2500","-"),ui=f("\u256E","+"),di=f("\u251C","+"),mi=f("\u256F","+"),hi=f("\u25CF","\u2022"),pi=f("\u25C6","*"),fi=f("\u25B2","!"),gi=f("\u25A0","x");var bi={light:f("\u2500","-"),heavy:f("\u2501","="),block:f("\u2588","#")};function Mt(){return`${It.gray(qt)} `}var yi=Mt();class Ve{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Me.homedir(),t=ue.join(e,".config","clapp");this.configPath=ue.join(t,"telemetry.json")}async isEnabled(){if(x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true")return!1;if(x.env.NO_TELEMETRY==="1"||x.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Me.platform(),nodeVersion:x.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Bt(this.configPath)){let e=await ce.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=ue.dirname(this.configPath);await ce.mkdir(t,{recursive:!0}),await ce.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Si=new Ve;var Ce="0.3.
|
|
32
|
+
`),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((d,n)=>{if(d.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let a={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(a);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,n=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...a,next:n})}else await m()};await n()}else await m();for(let d of i.afterHooks)await d(a);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Ae{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Wt=new Ae;function et(){if("FORCE_COLOR"in M.env)return M.env.FORCE_COLOR!=="0";if("NO_COLOR"in M.env||M.env.TERM==="dumb")return!1;if(M.platform==="win32")return!0;return qe.isatty(1)&&qe.isatty(2)}var Re=et();function g(e,t){if(!Re)return(i)=>i;return(i)=>e+i+t}var tt=g("\x1B[0m","\x1B[0m"),it=g("\x1B[31m","\x1B[39m"),st=g("\x1B[32m","\x1B[39m"),rt=g("\x1B[33m","\x1B[39m"),nt=g("\x1B[34m","\x1B[39m"),at=g("\x1B[35m","\x1B[39m"),ot=g("\x1B[36m","\x1B[39m"),lt=g("\x1B[37m","\x1B[39m"),ct=g("\x1B[90m","\x1B[39m"),ut=g("\x1B[1m","\x1B[22m"),dt=g("\x1B[3m","\x1B[23m"),mt=g("\x1B[4m","\x1B[24m"),ht=g("\x1B[2m","\x1B[22m"),pt=g("\x1B[7m","\x1B[27m"),ft=g("\x1B[8m","\x1B[28m"),gt=g("\x1B[9m","\x1B[29m"),bt=g("\x1B[41m","\x1B[49m"),yt=g("\x1B[42m","\x1B[49m"),$t=g("\x1B[43m","\x1B[49m"),vt=g("\x1B[44m","\x1B[49m"),wt=g("\x1B[45m","\x1B[49m"),xt=g("\x1B[46m","\x1B[49m"),Ct=g("\x1B[47m","\x1B[49m"),St=Re,Ot={reset:tt,red:it,green:st,yellow:rt,blue:nt,magenta:at,cyan:ot,white:lt,gray:ct,bold:ut,italic:dt,underline:mt,dim:ht,inverse:pt,hidden:ft,strikethrough:gt,bgRed:bt,bgGreen:yt,bgYellow:$t,bgBlue:vt,bgMagenta:wt,bgCyan:xt,bgWhite:Ct,isColorSupported:St},It=Ot,kt=["up","down","left","right","space","enter","cancel"],Kt={actions:new Set(kt),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var Yt=Et.platform.startsWith("win"),Qt=Symbol("clapp:cancel");var _t=Ge();var f=(e,t)=>_t?e:t,Jt=f("\u25C6","*"),Xt=f("\u25A0","x"),Zt=f("\u25B2","x"),ei=f("\u25C7","o"),ti=f("\u250C","T"),qt=f("\u2502","|"),ii=f("\u2514","\u2014"),si=f("\u25CF",">"),ri=f("\u25CB"," "),ni=f("\u25FB","[\u2022]"),ai=f("\u25FC","[+]"),oi=f("\u25FB","[ ]"),li=f("\u25AA","\u2022"),ci=f("\u2500","-"),ui=f("\u256E","+"),di=f("\u251C","+"),mi=f("\u256F","+"),hi=f("\u25CF","\u2022"),pi=f("\u25C6","*"),fi=f("\u25B2","!"),gi=f("\u25A0","x");var bi={light:f("\u2500","-"),heavy:f("\u2501","="),block:f("\u2588","#")};function Mt(){return`${It.gray(qt)} `}var yi=Mt();class Ve{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Me.homedir(),t=ue.join(e,".config","clapp");this.configPath=ue.join(t,"telemetry.json")}async isEnabled(){if(x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true")return!1;if(x.env.NO_TELEMETRY==="1"||x.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Me.platform(),nodeVersion:x.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Bt(this.configPath)){let e=await ce.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=ue.dirname(this.configPath);await ce.mkdir(t,{recursive:!0}),await ce.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Si=new Ve;var Ce="0.3.3";var u=new xe("query-builder");u.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(e,t)=>{await oe(e,t)});u.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(e)=>{let t=e?.table,i=t?Array.isArray(t)?t:[t]:void 0,s=await k({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
|
|
33
33
|
|
|
34
34
|
${s.map((a)=>a.source).join(`
|
|
35
35
|
`)}`)});u.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async(e,t,i)=>{await Te(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await pe()});u.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async(e)=>{try{await De(e)}catch{let t=await import("process");t.default.exitCode=1}});u.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async(e,t)=>{await we(e,t)});u.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async(e,t)=>{await se(e,t)});u.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate ./app/Models --dialect postgres").action(async(e,t)=>{try{await T(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full}),await C()}catch(i){console.error("-- Migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async(e)=>{await ie(e)});u.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async(e,t)=>{try{await q(e,{verbose:t.verbose,json:t.json})}catch(i){console.error("-- Explain all failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async(e)=>{try{await W({dir:e.dir,format:e.format,output:e.output,verbose:e.verbose})}catch(t){console.error("-- Diagram generation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async(e,t)=>{try{console.log("-- Resetting database..."),await R(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await T(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await C()}catch(i){console.error("-- Migrate fresh failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async(e,t)=>{try{await R(e,{dialect:t.dialect,state:t.state})}catch(i){console.error("-- Reset failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async(e)=>{try{if(e.class)await U(e.class,{verbose:e.verbose});else await A({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async(e)=>{try{if(e.class)await U(e.class,{verbose:e.verbose});else await A({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async(e)=>{try{await ye(e)}catch(t){console.error("-- Failed to create seeder:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async(e)=>{try{await be({modelsDir:e.models,seedersDir:e.seeders,verbose:e.verbose})}catch(t){console.error("-- Database fresh failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async(e,t)=>{try{await le(e,{table:t.table,dir:t.dir,timestamps:t.timestamps})}catch(i){console.error("-- Failed to create model:",i);let s=await import("process");s.default.exitCode=1}});u.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async(e,t)=>{try{await j(e,{dir:t.dir,json:t.json,verbose:t.verbose})}catch(i){console.error("-- Failed to show model:",i);let s=await import("process");s.default.exitCode=1}});u.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await F()}catch(e){console.error("-- Failed to get migration status:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await ge()}catch(e){console.error("-- Failed to list migrations:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async(e)=>{try{await he({steps:Number(e.steps),reverseSchema:e.reverseSchema,deleteFiles:Boolean(e.deleteFiles)})}catch(t){console.error("-- Rollback failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async(e,t)=>{try{await me(e,{dialect:t?.dialect,state:t?.state,apply:t?.apply,full:t?.full})}catch(i){console.error("-- Generate migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await _()}catch(e){console.error("-- Failed to get database info:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await re()}catch(e){console.error("-- Failed to get database stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async(e)=>{try{await L({dialect:e.dialect,force:e.force,verbose:e.verbose})}catch(t){console.error("-- Wipe failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async(e)=>{try{await I({dialect:e.dialect,aggressive:e.aggressive,tables:e.tables?e.tables.split(","):void 0,verbose:e.verbose})}catch(t){console.error("-- Optimize failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await O()}catch(e){console.error("-- Console failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await Z()}catch(e){console.error("-- Tinker failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async(e,t)=>{try{await K(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to inspect table:",i);let s=await import("process");s.default.exitCode=1}});u.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async(e,t)=>{try{await ae(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to get table info:",i);let s=await import("process");s.default.exitCode=1}});u.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await z()}catch(e){console.error("-- Failed to clear cache:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await Y()}catch(e){console.error("-- Failed to get cache stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async(e)=>{try{await X({size:e.size})}catch(t){console.error("-- Failed to configure cache:",t);let i=await import("process");i.default.exitCode=1}});u.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async(e)=>{try{await J({operations:e.operations,iterations:e.iterations?Number(e.iterations):void 0})}catch(t){console.error("-- Benchmark failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(e)=>{try{await V(e)}catch(t){console.error("-- Validation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(e)=>{try{await Se(e)}catch(t){console.error("-- Check failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async(e,t)=>{try{await ee(e,{format:t.format,output:t.output,limit:t.limit?Number(t.limit):void 0})}catch(i){console.error("-- Export failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async(e,t,i)=>{try{await te(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let a=await import("process");a.default.exitCode=1}});u.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async(e)=>{try{await ne({tables:e.tables,output:e.output})}catch(t){console.error("-- Dump failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("version","Show the version of the CLI").action(()=>{console.log(Ce)});u.version(Ce);u.help();u.parse();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{n,e,B,t,P,Be,Ge,r,b,f}from"./chunk-hjgcemhy.js";import{i,xe,ve}from"./chunk-c7m701dd.js";import{M,Ae,Me,N}from"./chunk-
|
|
2
|
+
import{n,e,B,t,P,Be,Ge,r,b,f}from"./chunk-hjgcemhy.js";import{i,xe,ve}from"./chunk-c7m701dd.js";import{M,Ae,Me,N}from"./chunk-axxs7680.js";import{c}from"./chunk-3xpe6b57.js";var Ar=import.meta.require;import{existsSync as Nt,mkdirSync as yr,mkdtempSync as Li,readdirSync as br,readFileSync as Ht,rmSync as hr,unlinkSync as vn,writeFileSync as Tr}from"fs";import{tmpdir as Ki}from"os";import{isAbsolute as Bi,join as wt}from"path";import Pn from"process";function wr(s){let o=2166136261;for(let l=0;l<s.length;l++)o^=s.charCodeAt(l),o=Math.imul(o,16777619)>>>0;return o.toString(36).padStart(7,"0").slice(-7)}function Cr(s,o=63){if(s.length<=o)return s;let l=`_${wr(s)}`;return s.slice(0,o-l.length)+l}function Ct(s,o){let l=`${s}_`,d=o.startsWith(l)?o:`${l}${o}`;return Cr(d)}class a{quoteIdentifier(s){return`\`${s.replace(/`/g,"``")}\``}getColumnType(s){switch(s.type){case"string":return`varchar(${s.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if(s.enumValues&&s.enumValues.length>0)return`ENUM(${s.enumValues.map((l)=>`'${l.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(s){return this.getColumnType(s)}getAutoIncrementClause(s){if(s.isPrimaryKey&&(s.type==="integer"||s.type==="bigint"))return"auto_increment";return""}getDefaultValue(s){if(!s.hasDefault||s.defaultValue===void 0)return"";let o=s.defaultValue;if(typeof o==="string"){let l=o.toUpperCase();if(l==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(l))return`default ${l}`;let g=`'${o.replace(/'/g,"''")}'`;if(s.type==="text"||s.type==="json"||s.type==="enum"&&!s.enumValues?.length)return`default (${g})`;return`default ${g}`}else if(typeof o==="number"||typeof o==="bigint")return`default ${o}`;else if(typeof o==="boolean")return`default ${o?1:0}`;else if(o instanceof Date)return`default '${o.toISOString()}'`;return""}createEnumType(s,o){return""}foreignKeyClauses(s){return s.columns.filter((o)=>o.references).map((o)=>{let l=o.references,d=`${s.table}_${o.name}_fk`,g=`CONSTRAINT ${this.quoteIdentifier(d)} FOREIGN KEY (${this.quoteIdentifier(o.name)}) REFERENCES ${this.quoteIdentifier(l.table)}(${this.quoteIdentifier(l.column)})`;if(l.onDelete)g+=` ON DELETE ${l.onDelete.toUpperCase()}`;if(l.onUpdate)g+=` ON UPDATE ${l.onUpdate.toUpperCase()}`;return g})}createTable(s){let o=[...s.columns.map((l)=>this.renderColumn(l)),...this.foreignKeyClauses(s)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
|
|
3
3
|
${o.join(`,
|
|
4
4
|
`)}
|
|
5
5
|
) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(s){let o=this.getColumnType(s).toLowerCase();if(o.includes("text")||o.includes("blob")||o==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let l=o.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(l!==void 0)return{bytes:Number(l)*a.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(s,o,l){let d=o.columns.map((x)=>{let y=l?.find((S)=>S.name===x),D=y?this.keyPartWidth(y):{bytes:0,indexableWhole:!0},E=!D.indexableWhole;return{name:x,prefixed:E,bytes:E?a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER:D.bytes,narrowable:!D.indexableWhole||D.bytes>a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}}),g=()=>d.reduce((x,y)=>x+y.bytes,0);while(g()>a.MAX_KEY_BYTES){let x=d.filter((y)=>y.narrowable&&!y.prefixed).sort((y,D)=>D.bytes-y.bytes)[0];if(!x)throw Error(`[migrations] Index '${o.name}' on table '${s}' needs ${g()} bytes of key, over MySQL's ${a.MAX_KEY_BYTES}. Every column in it is already at its ${a.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);x.prefixed=!0,x.bytes=a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}return d.map((x)=>x.prefixed?`${this.quoteIdentifier(x.name)}(${a.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(x.name))}createIndex(s,o,l){if(o.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${o.name}' on table '${s}' uses WHERE clause: ${o.where}`);let d=o.type==="unique"?"UNIQUE ":"",g=Ct(s,o.name),x=this.keyParts(s,o,l).join(", ");return`CREATE ${d}INDEX ${this.quoteIdentifier(g)} ON ${this.quoteIdentifier(s)} (${x});`}addForeignKey(s,o,l,d,g,x,y=[]){let D=`${s}_${o}_fk`,E=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(D)} FOREIGN KEY (${this.quoteIdentifier(o)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(d)})`;if(g)E+=` ON DELETE ${g.toUpperCase()}`;if(x)E+=` ON UPDATE ${x.toUpperCase()}`;let S=[...new Set(y)].map((v)=>`ALTER TABLE ${this.quoteIdentifier(s)} DROP FOREIGN KEY ${this.quoteIdentifier(v)};`).join(`
|
|
@@ -341,7 +341,7 @@ export default class ${g} extends Seeder {
|
|
|
341
341
|
return 100
|
|
342
342
|
}
|
|
343
343
|
}
|
|
344
|
-
`;pi(y,D),console.log(`-- \u2713 Created seeder: ${y}`)}async function be(s={}){let o=Zt(Wt.cwd()),l=s.modelsDir||qt(o,"app/Models"),d=s.seedersDir||qt(o,"database/seeders"),g=s.verbose??!0;try{let{resetDatabase:x,generateMigration:y,executeMigration:D}=await import("./chunk-
|
|
344
|
+
`;pi(y,D),console.log(`-- \u2713 Created seeder: ${y}`)}async function be(s={}){let o=Zt(Wt.cwd()),l=s.modelsDir||qt(o,"app/Models"),d=s.seedersDir||qt(o,"database/seeders"),g=s.verbose??!0;try{let{resetDatabase:x,generateMigration:y,executeMigration:D}=await import("./chunk-zbjamkgf.js");if(g)console.log("-- Refreshing database...");if(await x(l),g)console.log("-- Running migrations...");if(await y(l,{full:!0}),await D(),g)console.log("-- Running seeders...");if(await A({seedersDir:d,verbose:g}),g)console.log("-- \u2713 Database refreshed successfully")}catch(x){throw console.error("-- \u2717 Database refresh failed:",x),x}}function Te(s,o,l={}){let d=u({modelsDir:s}),g=$e(d);if(e.debug)e.debug.captureText=!0;let x=i({schema:g}),y=x.selectFrom(o).limit(Number(l.limit||10)).toText?.()??"";return console.log(y||"[query]"),{sql:y,qb:x,schema:g}}async function we(s,o={}){let l=i(),d=o.params?JSON.parse(o.params):void 0,g=await l.unsafe(s,d);return console.log(JSON.stringify(g)),g}import{existsSync as gi}from"fs";import{dirname as Jn,join as Zn}from"path";import er from"process";function yi(s){let o=s;while(o!==Jn(o)){if(gi(Zn(o,"package.json")))return o;o=Jn(o)}return er.cwd()}async function V(s){if(!s)s=Zn(yi(er.cwd()),"app/Models");let o=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${s}`),console.log(`-- Dialect: ${o}`),console.log();let l=[];try{let d=await u({modelsDir:s}),g=H(d,{dialect:o}),x=i(),y=[];if(o==="sqlite")y=(await x.unsafe(`
|
|
345
345
|
SELECT name FROM sqlite_master
|
|
346
346
|
WHERE type = 'table'
|
|
347
347
|
AND name NOT LIKE 'sqlite_%'
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ie}from"./chunk-4cs1xx1d.js";import{n,e,v,y,Pe,f,S,o,Je,Bt}from"./chunk-hjgcemhy.js";import{Database as ye}from"bun:sqlite";function M(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function pe(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 Ae(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}function Z(t){if(typeof t==="number")return{length:t};return t}function ce(t){if(typeof t==="number")return{max:t};return t}function Le(t){return typeof t==="function"}function Fe(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function be(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function V(t,r={}){if(!t)return r;return new Proxy(t,{get(s,i){if(i in r)return r[i];let a=s[i];if(a!==void 0)return a;let l=s[Fe(i)];if(Le(l))return l.bind(s);return}})}function $t(t){let r=(c)=>{let T=Array.isArray(c)?c:[],K=Math.floor(Math.random()*T.length);return T[K]},s=()=>t.string,i=()=>t.number,a=()=>t.random,l=V(t.string,{alpha:(c)=>s()?.alpha?.(Z(c)),alphanumeric:(c)=>s()?.alphanumeric?.(Z(c)),numeric:(c)=>s()?.numeric?.(Z(c)),sample:(c)=>s()?.sample?.(Z(c)),hexadecimal:(c)=>s()?.hexadecimal?.(Z(c))}),d=V(t.number,{int:(c)=>i()?.int?.(ce(c)),float:(c)=>{let T=ce(c);return be(Number(i()?.float?.(T)??0),T)}}),u=V(t.helpers,{arrayElement:r,arrayElements:(c,T)=>{let K=[...Array.isArray(c)?c:[]],D=typeof T==="number"?T:Math.max(1,Math.floor(Math.random()*K.length));for(let R=K.length-1;R>0;R-=1){let _=Math.floor(Math.random()*(R+1));[K[R],K[_]]=[K[_],K[R]]}return K.slice(0,Math.min(D,K.length))},shuffle:(c)=>{let T=[...Array.isArray(c)?c:[]];for(let K=T.length-1;K>0;K-=1){let D=Math.floor(Math.random()*(K+1));[T[K],T[D]]=[T[D],T[K]]}return T},maybe:(c,T)=>{let K=typeof T?.probability==="number"?T.probability:0.5;return Math.random()<K?c():void 0},slugify:(c)=>String(c??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),p={string:l,number:d,helpers:u,datatype:{boolean:(c)=>{let T=typeof c==="number"?c:c?.probability;if(typeof T==="number")return Math.random()<T;return Boolean(a()?.boolean?.())},number:(c)=>Number(i()?.int?.(ce(c))??0),float:(c)=>be(Number(i()?.float?.(c)??0),c),uuid:()=>crypto.randomUUID(),string:(c)=>String(s()?.alphanumeric?.({length:c??10})??""),hexadecimal:(c)=>String(s()?.hexadecimal?.(Z(c))??""),array:(c)=>Array.from({length:c??3},()=>s()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:s()?.alphanumeric?.({length:8})})},location:V(t.address),address:V(t.address),vehicle:V(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:V(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(c,T){if(T in p)return p[T];let K=c[T];if(K&&typeof K==="object")return V(K);return K}})}function Me(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 N(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Me).filter((s)=>s!==null)}function G(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Ce=/^[A-Z_][A-Z0-9_]*$/i;function q(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(!Ce.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function $e(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 s=t.split(".");if(s.length>2||s.some((i)=>i.length===0||i.length>64||!Ce.test(i)))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 we(t,r){if(r.length!==1)return r;let s=r[0];if(Array.isArray(s))return[...s];if(s===void 0&&Bt(t)===0)return[];return r}var se=null,Te=new Map;function We(t,r){Te.set(t,r),te.clear()}function Et(){Te.clear(),te.clear()}function B(t){if(!se)try{se=import.meta.require("./chunk-g2ryjpbk.js").getModel}catch{se=()=>{return}}return se(t)??Te.get(t)}var ie=new Map,Ue=500;function De(t){let r=ie.get(t);if(r!==void 0)return r;let s=Je(t,"postgres");if(ie.size>=Ue)ie.clear();return ie.set(t,s),s}function xt(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 vt(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 ge{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 s=this.sqliteDb.run(t,r);return Promise.resolve({changes:s.changes,lastInsertId:s.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class Se{dialect;constructor(t){this.dialect=t}conn(){return y()}text(t){return this.dialect==="postgres"?De(t):t}async all(t,r){let s=await this.conn().unsafe(this.text(t),r);return Array.isArray(s)?s:[]}async get(t,r){let s=await this.conn().unsafe(this.text(t),r);if(Array.isArray(s))return s[0]??void 0;return s??void 0}async run(t,r){let s=await this.conn().unsafe(this.text(t),r);return{changes:xt(s),lastInsertId:vt(s)}}async insert(t,r,s){if(this.dialect==="postgres"){let l=await this.conn().unsafe(`${De(t)} RETURNING ${s}`,r),d=Array.isArray(l)?l[0]:l;return{changes:1,lastInsertId:d?d[s]??null:null}}let i=await this.conn().unsafe(t,r),a=vt(i);if(a==null){let l=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);a=(Array.isArray(l)?l[0]:l)?.id??null}return{changes:xt(i)||1,lastInsertId:a}}}var H=null,de=!1,W=null,ee=null,ae=null,le=null;function Dn(t){if(t.database instanceof ye)H=t.database,de=!1;else H=new ye(t.database||":memory:",{create:!0}),de=!0,v(H);W=null,ee=null}function $n(){let t=de,r=H;if(H=null,de=!1,W=null,ee=null,ae=null,le=null,t&&r)try{r.close()}catch{}}var ke=!1;function C(){if(H){if(!W||ee!==H)W=new ge(H),ee=H,ae="sqlite",le=null;return W}let t=e.dialect,r=e.database?.database??null;if(W&&ee===null&&ae===t&&le===r)return W;if(ee=null,ae=t,le=r,t==="sqlite"){if(!r&&!ke)ke=!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 ye(r||":memory:",{create:!0});v(s),W=new ge(s)}else W=new Se(t);return W}function En(){let t=C();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,Ke=1000;function He(t,r,s){let i=t.attributes,a=new Map(Object.entries(i).map(([l,d])=>[E(l),d]));for(let l of r){let d=String(a.get(l)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let l of s)for(let d of r){let u=l[d];if(u===null||u===void 0||u instanceof Date)continue;let h=typeof u;if(h!=="string"&&h!=="number"&&h!=="boolean"&&h!=="bigint")return!1}return!0}function Qe(t,r){return typeof r==="bigint"?r.toString():r}function Re(t){return 2**Math.floor(Math.log2(t))}var j="deleted_at",_e=500,he="__btm_rel__";function J(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Y(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var xe=new WeakMap;function Ve(t){let r=xe.get(t);if(r)return r;let s=new Set,i=t.belongsToMany;if(i){if(Array.isArray(i)){for(let a of i)if(typeof a==="string")s.add(a.toLowerCase());else if(a&&typeof a==="object"&&a.model)s.add(a.model.toLowerCase())}else if(typeof i==="object")for(let a of Object.keys(i))s.add(a)}return xe.set(t,s),s}function Oe(t){let r={};for(let[s,i]of Object.entries(t))r[E(s)]=i;return r}function ze(t){for(let r in t)if(E(r)!==r)return Oe(t);return t}function Ge(t,r){if(t[r])return t[r];let s=E(r);if(t[s])return t[s];for(let i of Object.keys(t))if(E(i)===s)return t[i];return}class O{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,s){this._definition=t,this._exists=s,this._attributes=ze({...r}),this._original=null;let i=Ve(t);if(i.size===0)return;let a=this;return new Proxy(this,{get(l,d,u){if(typeof d==="string"&&i.has(d)&&!(d in l))return()=>{let h=Be(t,d);if(!h||h.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let p=B(h.relatedModelName),c=p?.getDefinition?.()||p?.definition;if(!c)throw Error(`[orm] related model '${h.relatedModelName}' is not registered`);return new kt(a,t,h,c)};return Reflect.get(l,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 s=r(this._attributes);if(s!==void 0)return s}catch{}return this._attributes[E(t)]}getAttribute(t){return this._attributes[E(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[E(t)]=r}only(t){let r={};for(let s of t)r[s]=this._attributes[E(s)];return r}except(t){let r=new Set(t.map((i)=>E(i))),s={};for(let i of Object.keys(this._attributes))if(!r.has(i))s[i]=this._attributes[i];return s}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=E(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()[E(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[s,i]of Object.entries(t)){let a=Ge(r,s),l=!a&&E(s).endsWith("_id");if(a?.fillable&&!a?.guarded||l){if(this._original===null)this._original={...this._attributes};this._attributes[E(s)]=i}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Oe(t);Object.assign(this._attributes,r);for(let s of Object.keys(r))this._forced.add(s);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,s=this._definition.attributes,i={};for(let[u,h]of Object.entries(s)){if(h.guarded&&!this._forced.has(E(u)))continue;let p=E(u);if(this._attributes[p]!==void 0)i[p]=this._attributes[p]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in i))i[u]=this._attributes[u];let a=this._attributes[t],d=s[t]?.guarded&&!this._forced.has(t);if(a!=null&&!(t in i)&&!d)i[t]=a;if(Y(this._definition)){let u=G(),h=this._attributes.created_at;i.created_at=h===void 0||h===null?u:h,i.updated_at=u}if(this._definition.traits?.useUuid&&!i.uuid)i.uuid=crypto.randomUUID();return await r?.beforeCreate?.(i),i}async _markInserted(t,r){let s=this._definition.primaryKey||"id";for(let[i,a]of Object.entries(t))this._attributes[i]=a;if(!(s in t)&&r!=null)this._attributes[s]=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,s]of Object.entries(t))if(this.isDirty(r))this._attributes[E(r)]=s(this._attributes)}async save(){let t=C(),r=this._definition.primaryKey||"id",s=this._definition.hooks;if(this._exists){this._applySetters(),await s?.beforeUpdate?.(this,this.getChanges());let i=this.getChanges(),a=Object.keys(i);if(a.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let l=a.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(i),this._attributes[r]];if(Y(this._definition)){let u=G();await t.run(`UPDATE ${this._definition.table} SET ${l}, updated_at = ? WHERE ${r} = ?`,[...Object.values(i),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${l} WHERE ${r} = ?`,d)}await s?.afterUpdate?.(this)}else{let i=await this._prepareInsert(),a=Object.keys(i),l=a.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${a.join(", ")}) VALUES (${l})`,Object.values(i),r);return await this._markInserted(i,r in i?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=C(),r=this._definition.primaryKey||"id",s=this._attributes[r];if(s==null)return null;let i=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[s]);if(!i)return null;return new O(this._definition,i,!0)}async delete(){let t=C(),r=this._definition.primaryKey||"id",s=this._attributes[r],i=this._definition.hooks;if(s==null)throw Error("Cannot delete a model without a primary key");if(await i?.beforeDelete?.(this),J(this._definition)){let a=G();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[a,s]),this._attributes[j]=a}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[s]);return await i?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],s=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await s?.beforeDelete?.(this),await C().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await s?.afterDelete?.(this),!0}async restore(){if(!J(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 C().run(`UPDATE ${this._definition.table} SET ${j} = ? WHERE ${t} = ?`,[null,r]),this._attributes[j]=null,this._original=null,this}trashed(){return this._attributes[j]!=null}async refresh(){let t=C(),r=this._definition.primaryKey||"id",s=this._attributes[r];if(!s)throw Error("Cannot refresh a model without a primary key");let i=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[s]);if(!i)return null;return this._attributes=i,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 O(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,s]of Object.entries(this._relations))if(Array.isArray(s))t[r]=s.map((i)=>i.toArray());else if(s)t[r]=s.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[s,i]of Object.entries(this._definition.attributes))if(i.hidden)t.add(s);let r={};for(let[s,i]of Object.entries(this._attributes))if(!t.has(s))r[s]=i;for(let[s,i]of Object.entries(this._relations))if(Array.isArray(i))r[s]=i.map((a)=>a.toJSON());else if(i)r[s]=i.toJSON();else r[s]=null;return r}}var Ee=new Map,ve=new Map,te=new Map,Xe=1000;function F(t){return E(t)}function E(t){let r=Ee.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Ee.set(t,r),r}function z(t){let r=ve.get(t);if(r!==void 0)return r;return r=Pe(t),ve.set(t,r),r}var ue=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ye=[...ue,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ne(t,r){let s=t[r];if(!s)return[];if(Array.isArray(s))return s.map((i)=>typeof i==="string"?i:String(i?.model??"")).filter(Boolean);if(typeof s==="object")return Object.keys(s);if(typeof s==="string")return[s];return[]}function Ze(t,r){let s=t.name??t.table??"model",a=Ye.filter((d)=>Ne(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!ue.includes(d));if(a.length>0)return`[orm] '${s}' declares '${r}' as ${a.join("/")}, which eager loading does not support yet. Supported kinds: ${ue.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let l=ue.flatMap((d)=>Ne(t,d));return l.length>0?`[orm] '${s}' has no relation '${r}'. Available: ${l.join(", ")}.`:`[orm] '${s}' has no relation '${r}' \u2014 it declares no relations at all.`}function Be(t,r){let{name:s,table:i}=t,a=t.primaryKey||"id";function l(w){if(!w)return null;if(Array.isArray(w)){for(let m of w){let k=typeof m==="string"?m:m?.model||"";if(k&&k.toLowerCase()===r.toLowerCase())return k}return null}if(typeof w==="object"){for(let[m,k]of Object.entries(w))if(m===r||m.toLowerCase()===r.toLowerCase())return typeof k==="string"?k:k?.model||k?.target||m}return null}function d(){let w=t.belongsTo;if(!w)return null;let m=r.toLowerCase(),k=(b)=>{if(typeof b==="string")return{model:b};if(b&&typeof b==="object"&&typeof b.model==="string")return{model:b.model,foreignKey:b.foreignKey};return null};if(Array.isArray(w)){for(let b of w){let g=k(b);if(g&&g.model.toLowerCase()===m)return g}return null}if(typeof w==="object"){for(let[b,g]of Object.entries(w))if(b===r||b.toLowerCase()===m)return k(g)}return null}function u(){let w=t.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let m of w)if(typeof m==="string"){if(m.toLowerCase()===r.toLowerCase())return{entry:m}}else if(m&&typeof m==="object"&&m.model){if(m.model.toLowerCase()===r.toLowerCase())return{entry:m}}return null}if(typeof w==="object"){for(let[m,k]of Object.entries(w))if(m===r||m.toLowerCase()===r.toLowerCase())return{entry:k}}return null}function h(w){let m=t[w];if(!m)return null;let k=r.toLowerCase();if(Array.isArray(m)){for(let b of m){let g=typeof b==="string"?b:String(b?.model??"");if(!g||g.toLowerCase()!==k)continue;let A=typeof b==="object"?b?.morphName:void 0;return{model:g,morphName:String(A??`${E(s)}able`)}}return null}if(typeof m==="object")for(let[b,g]of Object.entries(m)){let A=typeof g==="string"?g:String(g?.model??"");if(b.toLowerCase()!==k&&A.toLowerCase()!==k)continue;let P=typeof g==="object"?g?.morphName:void 0;return{model:A,morphName:String(P??b)}}return null}for(let w of["morphMany","morphOne"]){let m=h(w);if(!m)continue;let b=B(m.model)?.getTable?.()||z(m.model);return{type:w,relatedModelName:m.model,relatedTable:b,foreignKey:`${m.morphName}_id`,localKey:a,morphTypeColumn:`${m.morphName}_type`,morphTypeValue:i}}let p=l(t.hasMany);if(p){let m=B(p)?.getTable?.()||z(p),k=E(s)+"_id";return{type:"hasMany",relatedModelName:p,relatedTable:m,foreignKey:k,localKey:a}}let c=l(t.hasOne);if(c){let m=B(c)?.getTable?.()||z(c),k=E(s)+"_id";return{type:"hasOne",relatedModelName:c,relatedTable:m,foreignKey:k,localKey:a}}let T=d();if(T){let w=T.model,m=B(w),k=m?.getTable?.()||z(w),b=m?.getDefinition?.()?.primaryKey||"id",g=T.foreignKey||`${E(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:k,foreignKey:g,localKey:b}}let K=u();if(K){let w=typeof K.entry==="object",m=w?K.entry.model:K.entry,b=B(m)?.getTable?.()||z(m),g=w?K.entry:null,A,P;if(g?.table)A=g.table;else if(g?.through){P=g.through;let I=B(g.through);if(!I)throw Error(`[orm] belongsToMany relation '${r}' on '${s}' references unknown through model '${g.through}'. Make sure '${g.through}' is registered.`);A=I.getTable?.()||I.getDefinition?.()?.table||z(g.through)}else{let I=oe(i),U=oe(b);A=[I,U].sort().join("_")}let L=g?.foreignKey||`${oe(i)}_id`,X=g?.relatedKey||`${oe(b)}_id`,Q=[];if(g?.pivot?.columns)for(let I of Object.keys(g.pivot.columns))Q.push(I);if(P){let I=B(P),U=I?.getDefinition?.()||I?.definition,fe=U?.attributes??{},je=U?.primaryKey??"id";for(let re of Object.keys(fe)){if(re===L||re===X||re===je)continue;if(!Q.includes(re))Q.push(re)}}return{type:"belongsToMany",relatedModelName:m,relatedTable:b,foreignKey:L,localKey:a,pivotTable:A,pivotFkParent:L,pivotFkRelated:X,pivotColumns:Q,pivotModelName:P,pivotTimestamps:Boolean(g?.pivot?.timestamps)}}let D=(w,m)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let k=w[r]??w[Object.keys(w).find((U)=>U.toLowerCase()===r.toLowerCase())??""];if(!k||typeof k!=="object")return null;let{through:b,target:g}=k;if(!b||!g)return null;let A=B(b),P=A?.getDefinition?.()||A?.definition,L=A?.getTable?.()||P?.table||z(b),X=P?.primaryKey||"id",I=B(g)?.getTable?.()||z(g);return{type:m,relatedModelName:g,relatedTable:I,foreignKey:`${E(s)}_id`,localKey:a,throughTable:L,throughForeignKey:`${E(s)}_id`,throughLocalKey:X,targetForeignKey:`${oe(L)}_id`}},R=D(t.hasManyThrough,"hasManyThrough");if(R)return R;let _=D(t.hasOneThrough,"hasOneThrough");if(_)return _;return null}function me(t,r){let s=new Set;for(let i of t){let a=i.get(r);if(a!=null)s.add(a)}return[...s]}function oe(t){return f(e.relations?.singularizeStrategy)(t)}class kt{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,s,i){this._parent=t,this._parentDef=r,this._resolved=s,this._relatedDef=i}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,s){if(s===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[s]});return this}wherePivot(t,r,s){if(s===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[s]});return this}wherePivotIn(t,r){if(!r.length)return this;let s=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${s})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let s=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${s})`,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($e(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=[],s=`SELECT ${this.relatedSelectColumns().map((i)=>`${this.relatedTable}.${i} AS ${he}${i}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;s+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,s+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let i of this._pivotWheres)s+=` AND ${i.sql}`,t.push(...i.params);for(let i of this._wheres)s+=` AND ${i.sql}`,t.push(...i.params);if(this._orderBy.length>0)s+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)s+=` LIMIT ${this._limit}`;if(this._offset!==void 0)s+=` OFFSET ${this._offset}`;return{sql:s,params:t}}hydrateRows(t){let r=this.fkParent,s=this.fkRelated;return t.map((i)=>{let a={},l={};for(let[u,h]of Object.entries(i))if(u.startsWith(he))a[u.slice(he.length)]=h;else if(u!==r&&u!==s)l[u]=h;let d=new O(this._relatedDef,a,!0);return d.pivot=l,d})}async get(){let t=C(),{sql:r,params:s}=this.buildSelect(),i=await t.all(r,s);return this.hydrateRows(i)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=C(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];for(let a of this._pivotWheres)r+=` AND ${a.sql}`,s.push(...a.params);let i=await t.get(r,s);return Number(i?.count??0)}async exists(){return await this.count()>0}now(){return G()}async attach(t,r={}){let s=C(),i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=this._resolved.pivotTimestamps?this.now():null,l=0;for(let d of i){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(a){if(u.created_at===void 0)u.created_at=a;if(u.updated_at===void 0)u.updated_at=a}let h=Object.keys(u),p=h.map(()=>"?").join(", "),c=`INSERT INTO ${this.pivotTable} (${h.join(", ")}) VALUES (${p})`,T=h.map((K)=>u[K]);await s.run(c,T),l++}return l}async detach(t){let r=C(),s=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,i=[this.parentId];if(t!==void 0&&t!==null){let a=Array.isArray(t)?t:[t];if(a.length===0)return 0;let l=a.map(()=>"?").join(", ");s+=` AND ${this.fkRelated} IN (${l})`,i.push(...a)}return(await r.run(s,i)).changes}async updateExistingPivot(t,r){let s=C(),i={...r};if(this._resolved.pivotTimestamps&&i.updated_at===void 0)i.updated_at=this.now();let a=Object.keys(i);if(a.length===0)return 0;let l=a.map((h)=>`${h} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${l} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...a.map((h)=>i[h]),this.parentId,t];return(await s.run(d,u)).changes}async sync(t){let r=C(),s=new Map;for(let p of t)if(p!=null&&typeof p==="object"&&"id"in p){let{id:c,...T}=p;s.set(c,T)}else s.set(p,{});let i=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),a=new Set(i.map((p)=>p[this.fkRelated])),l=[],d=[],u=[],h=[...a].filter((p)=>!s.has(p));if(h.length>0)await this.detach(h),d.push(...h);for(let[p,c]of s)if(!a.has(p))await this.attach(p,c),l.push(p);else if(Object.keys(c).length>0)await this.updateExistingPivot(p,c),u.push(p);return{attached:l,detached:d,updated:u}}async toggle(t){let r=C(),s=Array.isArray(t)?t:[t];if(s.length===0)return{attached:[],detached:[]};let i=s.map(()=>"?").join(", "),a=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${i})`,[this.parentId,...s]),l=new Set(a.map((h)=>h[this.fkRelated])),d=s.filter((h)=>!l.has(h)),u=s.filter((h)=>l.has(h));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class x{_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,s){if(s===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:s,boolean:"and"});return this}orWhere(t,r,s){if(s===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:s,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 q(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return q(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return q(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return q(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:we(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:we(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let s=new x(this._definition);if(r(s),s._wheres.length===0)return this;let i=[],a=s.buildWhereClauses(i);if(!a)return this;return this._wheres.push({raw:`(${a})`,rawParams:i,boolean:t}),this}whereBetween(t,r){return q(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){q(t,"whereNotBetween(column)");let s=F(t);return this._wheres.push({raw:`(${s} < ? OR ${s} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if($e(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 s of this._wheres){let i;if(s.raw){if(i=s.raw,s.rawParams&&s.rawParams.length>0)t.push(...s.rawParams)}else if(s.value===null){let a=F(s.column);i=s.operator==="="?`${a} IS NULL`:`${a} IS NOT NULL`}else if(s.operator==="in"||s.operator==="not in"){let a=s.value;i=o(F(s.column),a,s.operator==="not in",a.map(()=>"?").join(", ")),t.push(...a)}else i=`${F(s.column)} ${s.operator} ?`,t.push(s.value);r.push({conn:s.boolean==="or"?"OR":"AND",sql:i})}return S(r)}softDeleteClause(){if(this._trashed==="include"||!J(this._definition))return"";return this._trashed==="only"?`${j} IS NOT NULL`:`${j} 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):"",s=this.softDeleteClause();if(r&&s)return`(${r}) AND ${s}`;return r||s}buildQuery(){let t=[],s=`SELECT ${this._select.map((a)=>a==="*"?a:F(a)).join(", ")} FROM ${this._definition.table}`,i=this.composeWhere(t);if(i)s+=` WHERE ${i}`;if(this._orderBy.length>0)s+=` ORDER BY ${this._orderBy.map((a)=>`${F(a.column)} ${a.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)s+=` LIMIT ${this._limit}`;if(this._offset!==void 0)s+=` OFFSET ${this._offset}`;return{sql:s,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 s=C(),i=this._definition.primaryKey||"id",a=`${this._definition.name}:${t}`,l=te.get(a);if(l===void 0){if(l=Be(this._definition,t),te.size>=Xe)te.clear();te.set(a,l)}if(!l)throw Error(Ze(this._definition,t));let d=l.type==="hasOne"||l.type==="morphOne";if(l.type==="hasMany"||l.type==="hasOne"||l.type==="morphMany"||l.type==="morphOne"){let u=me(r,i);if(u.length===0)return;let h=u.map(()=>"?").join(", "),p=l.morphTypeColumn?` AND ${l.morphTypeColumn} = ?`:"",c=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${l.foreignKey} IN (${h})${p}`,l.morphTypeColumn?[...u,l.morphTypeValue]:u),T=B(l.relatedModelName),K=T?.getDefinition?.()||T?.definition||this._definition;if(!d){let D=new Map;for(let R of c){let _=R[l.foreignKey];if(!D.has(_))D.set(_,[]);D.get(_).push(R)}for(let R of r){let _=D.get(R.get(i))||[];R.setRelation(t,_.map((w)=>new O(K,w,!0)))}}else{let D=new Map;for(let R of c){let _=R[l.foreignKey];if(!D.has(_))D.set(_,R)}for(let R of r){let _=D.get(R.get(i));R.setRelation(t,_?new O(K,_,!0):null)}}}if(l.type==="belongsTo"){let u=new Set;for(let R of r){let _=R._attributes[l.foreignKey];if(_!=null)u.add(_)}let h=[...u];if(h.length===0)return;let p=h.map(()=>"?").join(", "),c=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${l.localKey} IN (${p})`,h),T=B(l.relatedModelName),K=T?.getDefinition?.()||T?.definition||this._definition,D=new Map;for(let R of c)D.set(R[l.localKey],R);for(let R of r){let _=R._attributes[l.foreignKey],w=D.get(_);R.setRelation(t,w?new O(K,w,!0):null)}}if(l.type==="belongsToMany"){let u=me(r,i);if(u.length===0)return;if(!l.pivotTable||!l.pivotFkParent||!l.pivotFkRelated)return;let h=u.map(()=>"?").join(", "),p=await s.all(`SELECT * FROM ${l.pivotTable} WHERE ${l.pivotFkParent} IN (${h})`,u);if(p.length===0){for(let b of r)b.setRelation(t,[]);return}let c=new Set;for(let b of p){let g=b[l.pivotFkRelated];if(g!=null)c.add(g)}let T=[...c],K=B(l.relatedModelName),D=K?.getDefinition?.()||K?.definition||this._definition,R=D?.primaryKey||"id",_=[];if(T.length>0){let b=T.map(()=>"?").join(", ");_=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${R} IN (${b})`,T)}let w=new Map;for(let b of _)w.set(b[R],b);let m=new Map;for(let b of p){let g=b[l.pivotFkParent];if(!m.has(g))m.set(g,[]);m.get(g).push(b)}let k=new Set([l.pivotFkParent,l.pivotFkRelated]);for(let b of r){let g=b.get(i),P=(m.get(g)||[]).map((L)=>{let X=w.get(L[l.pivotFkRelated]);if(!X)return null;let Q=new O(D,X,!0),I={};for(let[U,fe]of Object.entries(L))if(!k.has(U))I[U]=fe;return Q.pivot=I,Q}).filter((L)=>L!==null);b.setRelation(t,P)}}if(l.type==="hasManyThrough"||l.type==="hasOneThrough"){let u=me(r,i);if(u.length===0)return;let h=l.throughLocalKey||"id",p=u.map(()=>"?").join(", "),c=await s.all(`SELECT ${h}, ${l.throughForeignKey} FROM ${l.throughTable} WHERE ${l.throughForeignKey} IN (${p})`,u);if(c.length===0){for(let k of r)k.setRelation(t,l.type==="hasManyThrough"?[]:null);return}let T=new Map;for(let k of c)T.set(k[h],k[l.throughForeignKey]);let K=[...new Set(c.map((k)=>k[h]))],D=K.map(()=>"?").join(", "),R=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${l.targetForeignKey} IN (${D})`,K),_=B(l.relatedModelName),w=_?.getDefinition?.()||_?.definition||this._definition,m=new Map;for(let k of R){let b=T.get(k[l.targetForeignKey]);if(b==null)continue;if(!m.has(b))m.set(b,[]);m.get(b).push(new O(w,k,!0))}for(let k of r){let b=m.get(k.get(i))||[];k.setRelation(t,l.type==="hasManyThrough"?b:b[0]??null)}}}async get(){let t=C(),{sql:r,params:s}=this.buildQuery(),a=(await t.all(r,s)).map((l)=>new O(this._definition,l,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(a);return a}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=C(),r=[],s=`SELECT COUNT(*) as count FROM ${this._definition.table}`,i=this.composeWhere(r);if(i)s+=` WHERE ${i}`;let a=await t.get(s,r);return Number(a?.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){q(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let s=C(),i=[r],a=F(t),l=`UPDATE ${this._definition.table} SET ${a} = ${a} + ?`;if(Y(this._definition))l+=", updated_at = ?",i.push(G());let d=this.composeWhere(i);if(d)l+=` WHERE ${d}`;return(await s.run(l,i)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let s=0;while(!0){let i=new x(this._definition);i._wheres=[...this._wheres],i._orderBy=[...this._orderBy],i._select=[...this._select],i._withRelations=[...this._withRelations],i._trashed=this._trashed,i._limit=t,i._offset=s*t;let a=await i.get();if(a.length===0)break;if(await r(a)===!1)break;if(a.length<t)break;s++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let l=t;r=l.perPage??15,t=l.page??1}let s=await this.count(),i=Math.ceil(s/r);this._limit=r,this._offset=(t-1)*r;let a=await this.get();return{data:a,total:s,page:t,perPage:r,lastPage:i,hasMorePages:t<i,isEmpty:a.length===0,from:a.length>0?(t-1)*r+1:null,to:a.length>0?(t-1)*r+a.length:null,meta:{perPage:r,page:t,total:s,lastPage:i}}}async pluck(t){q(t,"pluck(column)");let r=C(),s=[],i=F(t),a=`SELECT ${i} FROM ${this._definition.table}`,l=this.composeWhere(s);if(l)a+=` WHERE ${l}`;if(this._orderBy.length>0)a+=` ORDER BY ${this._orderBy.map((u)=>`${F(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)a+=` LIMIT ${this._limit}`;if(this._offset!==void 0)a+=` OFFSET ${this._offset}`;return(await r.all(a,s)).map((u)=>u[i])}async aggregate(t,r){q(r,`${t}(column)`);let s=C(),i=[],a=`SELECT ${t}(${F(r)}) as v FROM ${this._definition.table}`,l=this.composeWhere(i);if(l)a+=` WHERE ${l}`;let u=(await s.get(a,i))?.v;if(u==null)return null;if(typeof u==="string"){let h=Number(u);return u.trim()!==""&&!Number.isNaN(h)?h: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=J(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=C(),s=this._definition.table,i=this._definition.hooks,a=[],l=this.composeWhere(a);if(t&&this._trashed==="include")l=l?`(${l}) AND ${j} IS NULL`:`${j} IS NULL`;let d=l?` WHERE ${l}`:"",u=t?G():void 0;if(!i?.beforeDelete&&!i?.afterDelete)return t?(await r.run(`UPDATE ${s} SET ${j} = ?${d}`,[u,...a])).changes:(await r.run(`DELETE FROM ${s}${d}`,a)).changes;let h=this._definition.primaryKey||"id",c=(await r.all(`SELECT * FROM ${s}${d}`,a)).map((D)=>new O(this._definition,D,!0)),T=c.map((D)=>D._attributes[h]);if(T.some((D)=>D==null))throw Error(`Cannot delete a model without a primary key: '${h}' is missing from a matching row`);for(let D of c)await i.beforeDelete?.(D);let K=0;for(let D=0;D<T.length;D+=_e){let R=T.slice(D,D+_e),_=`${h} IN (${R.map(()=>"?").join(", ")})`;K+=t?(await r.run(`UPDATE ${s} SET ${j} = ? WHERE ${_}`,[u,...R])).changes:(await r.run(`DELETE FROM ${s} WHERE ${_}`,R)).changes}for(let D of c){if(t)D._attributes[j]=u;await i.afterDelete?.(D)}return K}async update(t){this.assertNoUnappliedClauses("update");let r=C(),s=Object.entries(t),i=s.map(([u])=>`${F(u)} = ?`).join(", "),a=s.map(([,u])=>u);if(Y(this._definition))a.push(G());let l=`UPDATE ${this._definition.table} SET ${i}${Y(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(a);if(d)l+=` WHERE ${d}`;return(await r.run(l,a)).changes}}function et(t){let r={query:()=>new x(t),where(s,i,a){return new x(t).where(s,i,a)},orWhere(s,i,a){return new x(t).orWhere(s,i,a)},whereIn(s,i){return new x(t).whereIn(s,i)},whereNotIn(s,i){return new x(t).whereNotIn(s,i)},whereNull(s){return new x(t).whereNull(s)},whereNotNull(s){return new x(t).whereNotNull(s)},whereLike(s,i){return new x(t).whereLike(s,i)},orderBy(s,i="asc"){return new x(t).orderBy(s,i)},orderByDesc(s){return new x(t).orderByDesc(s)},select(...s){return new x(t).select(...s)},with(...s){return new x(t).with(...s)},limit:(s)=>new x(t).limit(s),take:(s)=>new x(t).take(s),skip:(s)=>new x(t).skip(s),withTrashed:()=>new x(t).withTrashed(),onlyTrashed:()=>new x(t).onlyTrashed(),async find(s){let i=C(),a=t.primaryKey||"id",l=J(t)?` AND ${j} IS NULL`:"",d=await i.get(`SELECT * FROM ${t.table} WHERE ${a} = ?${l}`,[s]);return d?new O(t,d,!0):void 0},async findOrFail(s){let i=await r.find(s);if(!i)throw Error(`${t.name} with id ${s} not found`);return i},async findMany(s){let i=C(),a=t.primaryKey||"id",l=J(t)?` AND ${j} IS NULL`:"";return(await i.all(`SELECT * FROM ${t.table} WHERE ${a} IN (${s.map(()=>"?").join(", ")})${l}`,s)).map((u)=>new O(t,u,!0))},all:()=>new x(t).get(),first:()=>new x(t).first(),firstOrFail:()=>new x(t).firstOrFail(),last:()=>new x(t).last(),count:()=>new x(t).count(),exists:()=>new x(t).exists(),doesntExist:()=>new x(t).doesntExist(),paginate:(s,i)=>new x(t).paginate(s,i),whereBetween(s,i){return new x(t).whereBetween(s,i)},whereNotBetween(s,i){return new x(t).whereNotBetween(s,i)},async create(s){let i=new O(t,s,!1);return await i.save(),i},async createMany(s){let i=s.map((h)=>new O(t,h,!1));if(!i.length)return[];let a=C(),l=t.primaryKey||"id",d=[];for(let h of i)d.push(await h._prepareInsert());let u=new Map;d.forEach((h,p)=>{let c=Object.keys(h).join("\x00"),T=u.get(c);if(T)T.push(p);else u.set(c,[p])});for(let[h,p]of u){let c=h?h.split("\x00"):[],T=!c.includes(l);if(!c.length||T&&a.dialect==="mysql"){for(let D of p){let R=d[D],_=Object.keys(R),w=await a.insert(_.length?`INSERT INTO ${t.table} (${_.join(", ")}) VALUES (${_.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(R),l);await i[D]._markInserted(R,T?w.lastInsertId:void 0)}continue}if(a.dialect==="postgres"&&He(t,c,p.map((D)=>d[D]))){let D=t.table,R=c.join(", "),_=`INSERT INTO ${D} (${R}) SELECT ${R} FROM jsonb_populate_recordset(NULL::${D}, (?::text)::jsonb)`;for(let w=0;w<p.length;w+=Ke){let m=p.slice(w,w+Ke),k=JSON.stringify(m.map((A)=>Object.fromEntries(c.map((P)=>[P,d[A][P]??null]))),Qe);if(!T){await a.run(_,[k]);for(let A of m)await i[A]._markInserted(d[A]);continue}let b=(await a.all(`${_} RETURNING ${l}`,[k])).map((A)=>A[l]),g=b.every((A)=>typeof A==="number"||typeof A==="bigint")?[...b].sort((A,P)=>A<P?-1:A>P?1:0):b;for(let A=0;A<m.length;A++)await i[m[A]]._markInserted(d[m[A]],g[A])}continue}let K=Re(Math.max(1,Math.floor(qe/c.length)));for(let D=0;D<p.length;){let R=Math.min(K,Re(p.length-D)),_=p.slice(D,D+R);D+=R;let w=`INSERT INTO ${t.table} (${c.join(", ")}) VALUES ${_.map(()=>`(${c.map(()=>"?").join(", ")})`).join(", ")}`,m=_.flatMap((g)=>c.map((A)=>d[g][A]));if(!T){await a.run(w,m);for(let g of _)await i[g]._markInserted(d[g]);continue}let k=(await a.all(`${w} RETURNING ${l}`,m)).map((g)=>g[l]),b=k.every((g)=>typeof g==="number"||typeof g==="bigint")?[...k].sort((g,A)=>g<A?-1:g>A?1:0):k;for(let g=0;g<_.length;g++)await i[_[g]]._markInserted(d[_[g]],b[g])}}return i},async updateOrCreate(s,i){let a=new x(t);for(let[d,u]of Object.entries(s))a=a.where(d,u);let l=await a.first();if(l)return await l.update(i),l;return this.create({...s,...i})},async firstOrCreate(s,i){let a=new x(t);for(let[d,u]of Object.entries(s))a=a.where(d,u);return await a.first()||this.create({...s,...i})},async update(s,i){let a=await r.findOrFail(s);return await a.update(i),a},async delete(s){let i=await r.find(s);return i?i.delete():!1},destroy(s){return r.delete(s)},async forceDelete(s){let i=await r.withTrashed().find(s);return i?i.forceDelete():!1},remove(s){return r.forceDelete(s)},async truncate(){await C().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(s={}){return new O(t,s,!1)},latest:(s="created_at")=>new x(t).orderByDesc(s),oldest:(s="created_at")=>new x(t).orderBy(s,"asc"),max:(s)=>new x(t).max(s),min:(s)=>new x(t).min(s),avg:(s)=>new x(t).avg(s),sum:(s)=>new x(t).sum(s),pluck(s){return new x(t).pluck(s)}};return new Proxy(r,{get(s,i){if(typeof i==="string"&&i.startsWith("where")&&i.length>5){let a=i.slice(5),l=a.charAt(0).toLowerCase()+a.slice(1);if(l in t.attributes||l==="id"||l===t.primaryKey)return(d)=>new x(t).where(l,d)}return Reflect.get(s,i)}})}function Ct(t){let r=et(t);if(t?.name)We(t.name,r);return r}async function xn(t){let r=C(),s=E(t.primaryKey||"id"),i=[],a=new Set([s]);if(i.push(t.autoIncrement!==!1?`${s} INTEGER PRIMARY KEY AUTOINCREMENT`:`${s} INTEGER PRIMARY KEY`),t.traits?.useUuid)i.push("uuid TEXT UNIQUE"),a.add("uuid");for(let[l,d]of Object.entries(t.attributes)){let u=E(l);if(a.has(u))continue;a.add(u);let h=pe(d.type),p=Ae(h);if(u.endsWith("_id")&&(h===void 0||M(h)))p="INTEGER";let c=`${u} ${p}`;if(d.unique)c+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let T=d.foreignKey;if(c+=` REFERENCES ${T.table}(${T.column??"id"})`,T.onDelete)c+=` ON DELETE ${T.onDelete.toUpperCase()}`;if(T.onUpdate)c+=` ON UPDATE ${T.onUpdate.toUpperCase()}`}i.push(c)}for(let l of N(t.belongsTo)){let d=l.foreignKey??`${E(l.model)}_id`;if(a.has(d))continue;a.add(d),i.push(`${d} INTEGER`)}if(Y(t))for(let l of["created_at","updated_at"]){if(a.has(l))continue;a.add(l),i.push(`${l} TEXT`)}if(J(t)&&!a.has("deleted_at"))a.add("deleted_at"),i.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${i.join(", ")})`,[])}async function vn(t,r,s){let i=C(),a=t.traits?.useSeeder,l=r??(typeof a==="object"&&a?a.count:10);if(!s)try{let d=await import("./chunk-r2ta1rnj.js");s=$t(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<l;d++){let u={};for(let[p,c]of Object.entries(t.attributes))if(c.factory)u[E(p)]=c.factory(s);if(Y(t)){let p=G();u.created_at=p,u.updated_at=p}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let h=Object.keys(u);await i.run(`INSERT INTO ${t.table} (${h.join(", ")}) VALUES (${h.map(()=>"?").join(", ")})`,Object.values(u))}}var ne=new Map;function Wt(t){return ne.get(t)}function Ut(){return[...ne.values()]}function Vt(){return Object.fromEntries(ne)}function Ht(t){return ne.has(t)}function Qt(){ne.clear(),Et()}function Rt(t,r){return ne.set(t,r),r}function tt(){return typeof window<"u"&&typeof document<"u"}function Gt(t){let r;if(tt())r=Ie(t);else{let s=Ct(t);r=Object.assign(s,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return Rt(t.name,r),r}function Jt(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
|
|
3
|
+
export{M,Ae,$t,Me,N,Et,xt,vt,Dn,$n,En,kt,Ct,xn,vn,Wt,Ut,Vt,Ht,Qt,Rt,Gt,Jt};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Wt,Ut,Vt,Ht,Qt,Rt,Gt,Jt}from"./chunk-
|
|
2
|
+
import{Wt,Ut,Vt,Ht,Qt,Rt,Gt,Jt}from"./chunk-axxs7680.js";import"./chunk-hjgcemhy.js";import"./chunk-4cs1xx1d.js";export{Qt as clearModelRegistry,Gt as defineModel,Ut as getAllModels,Wt as getModel,Vt as getModelRegistry,Ht as hasModel,Jt as registerBrowserModels,Rt as registerModel};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{et,T,C,R}from"./chunk-
|
|
2
|
+
import{et,T,C,R}from"./chunk-5eatvs7h.js";import"./chunk-c7m701dd.js";import"./chunk-3xpe6b57.js";import"./chunk-axxs7680.js";import"./chunk-hjgcemhy.js";import"./chunk-4cs1xx1d.js";export{C as executeMigration,T as generateMigration,R as resetDatabase,et as saveMigrationSnapshot};
|
package/dist/orm.d.ts
CHANGED
|
@@ -63,6 +63,7 @@ export declare interface TypedAttribute<T = unknown> {
|
|
|
63
63
|
hidden?: boolean
|
|
64
64
|
guarded?: boolean
|
|
65
65
|
nullable?: boolean
|
|
66
|
+
required?: boolean
|
|
66
67
|
default?: InferType<T>
|
|
67
68
|
foreignKey?: boolean | import('./schema').ForeignKeyConfig
|
|
68
69
|
validation?: {
|
|
@@ -423,15 +424,48 @@ type FillableAttributes<TDef extends ModelDefinition> = Partial<Pick<
|
|
|
423
424
|
// Already nullable: nothing to add.
|
|
424
425
|
null extends ModelAttributes<TDef>[K]
|
|
425
426
|
? ModelAttributes<TDef>[K]
|
|
426
|
-
// Optional,
|
|
427
|
-
// write CLEARS it, which is different from omitting the key.
|
|
427
|
+
// Optional, or a column the migration creates without NOT NULL: `null`
|
|
428
|
+
// is how a write CLEARS it, which is different from omitting the key.
|
|
428
429
|
: undefined extends ModelAttributes<TDef>[K]
|
|
429
430
|
? ModelAttributes<TDef>[K] | null
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
431
|
+
: K extends NullableColumnKeys<TDef>
|
|
432
|
+
? ModelAttributes<TDef>[K] | null
|
|
433
|
+
// Required: null stays rejected, as the NOT NULL column would reject it.
|
|
434
|
+
: ModelAttributes<TDef>[K]
|
|
435
|
+
} & BelongsToCamelColumns<TDef>,
|
|
436
|
+
FillableKeys<TDef> | SnakeCase<FillableKeys<TDef>> | BelongsToKeys<TDef> | CamelCase<BelongsToKeys<TDef>>
|
|
434
437
|
>>
|
|
438
|
+
/**
|
|
439
|
+
* Whether the migration generator creates this attribute's column without
|
|
440
|
+
* NOT NULL. Mirrors `migrations.ts`: `nullable ?? !(required ?? validator
|
|
441
|
+
* .required())`. A plain `schema.string()` infers `string`, not
|
|
442
|
+
* `string | undefined`, so the check above never saw it as optional - and a
|
|
443
|
+
* write clearing a nullable column (`{ cwd: null }`) was a type error against
|
|
444
|
+
* a column the database had just been told could hold null.
|
|
445
|
+
*/
|
|
446
|
+
declare type IsNullableColumn<TAttr> = TAttr extends { nullable: true } ? true
|
|
447
|
+
: TAttr extends { nullable: false } ? false
|
|
448
|
+
: TAttr extends { required: true } ? false
|
|
449
|
+
: TAttr extends { required: false } ? true
|
|
450
|
+
: TAttr extends { validation: { rule: { readonly __isRequired: true } } } ? false
|
|
451
|
+
: true;
|
|
452
|
+
declare type NullableAttributeKeys<TDef extends ModelDefinition> = {
|
|
453
|
+
[K in AttributeKeys<TDef>]: IsNullableColumn<TDef['attributes'][K]> extends true ? K : never
|
|
454
|
+
}[AttributeKeys<TDef>];
|
|
455
|
+
// `belongsTo` FK columns are created nullable, like any unrequired column.
|
|
456
|
+
declare type NullableColumnKeys<TDef extends ModelDefinition> = | NullableAttributeKeys<TDef>
|
|
457
|
+
| SnakeCase<NullableAttributeKeys<TDef>>
|
|
458
|
+
| BelongsToKeys<TDef>;
|
|
459
|
+
declare type CamelCase<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S;
|
|
460
|
+
/**
|
|
461
|
+
* `conversationId` as well as `conversation_id`: every write key is
|
|
462
|
+
* normalized to snake_case before it reaches SQL (`normalizeAttributeKeys`),
|
|
463
|
+
* so the camelCase spelling already worked at runtime - and declared
|
|
464
|
+
* attributes accept both - but the type only admitted the column name.
|
|
465
|
+
*/
|
|
466
|
+
declare type BelongsToCamelColumns<TDef extends ModelDefinition> = {
|
|
467
|
+
[K in Exclude<BelongsToKeys<TDef>, DeclaredColumns<TDef>> as CamelCase<K>]: number | null
|
|
468
|
+
}
|
|
435
469
|
// Numeric attribute columns - constrains aggregate methods (sum, avg, etc.)
|
|
436
470
|
declare type NumericColumns<TDef extends ModelDefinition> = {
|
|
437
471
|
[K in AttributeKeys<TDef>]: InferAttributeType<TDef['attributes'][K]> extends number ? K : never
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{J,z,Y,X,O,Z,ee,te,ne,_,re,I,L,ie,se,K,ae,oe,Xe,Le,Ze,k,le,a,ce,ue,de,fe,m,et,T,C,R,me,he,F,ge,j,pe,q,W,A,U,ye,be,Te,we,V,Se,De,w,h,an,on,ln,tt,nt,rt,it,st,cn,at,Pt,un,dn,fn,mn,ot,hn,gn,pn,$e,u,lt,ct,ut,dt,ft,Ot,H,Ee,yn,bn,mt,Ke,p,Fe,je,_t,Tn,It,wn,ht,gt,pt,Lt,Kt}from"../chunk-
|
|
2
|
+
import{J,z,Y,X,O,Z,ee,te,ne,_,re,I,L,ie,se,K,ae,oe,Xe,Le,Ze,k,le,a,ce,ue,de,fe,m,et,T,C,R,me,he,F,ge,j,pe,q,W,A,U,ye,be,Te,we,V,Se,De,w,h,an,on,ln,tt,nt,rt,it,st,cn,at,Pt,un,dn,fn,mn,ot,hn,gn,pn,$e,u,lt,ct,ut,dt,ft,Ot,H,Ee,yn,bn,mt,Ke,p,Fe,je,_t,Tn,It,wn,ht,gt,pt,Lt,Kt}from"../chunk-5eatvs7h.js";import{D,Sn,Ft,l,yt,bt,i,xe,ve}from"../chunk-c7m701dd.js";import{Tt,c,Q,E,wt,qe,x,ke,We,Ue,Ce,St,d,G,Re,Ve,Dt,He,jt,qt}from"../chunk-3xpe6b57.js";import{$t,Et,xt,vt,Dn,$n,En,kt,Ct,xn,vn,Wt,Ut,Vt,Ht,Qt,Rt,Gt,Jt}from"../chunk-axxs7680.js";import{n,Qe,e,B,t,s,P,Ne,zt,At,Mt,v,Yt,Pe,b,Xt,Zt,f,Je}from"../chunk-hjgcemhy.js";import{en,tn,nn,g,ze,Ye,rn,Ie,sn}from"../chunk-4cs1xx1d.js";export{kt as BelongsToManyRelationBuilder,ze as BrowserQueryBuilder,g as BrowserQueryError,At as DEFAULT_SQLITE_PRAGMAS,Q as DynamoDBClient,Tt as DynamoDBDriverImpl,h as DynamoDBItemBuilder,Re as DynamoDBMigrationDriver,G as DynamoDBMigrationTracker,w as DynamoDBQueryBuilder,ot as DynamoDBToolingAdapter,He as EntityQueryBuilder,ut as GENERATED_MARKER,d as MIGRATIONS_TABLE,qe as Model,a as MySQLDriver,ce as PostgresDriver,fe as SQLiteDriver,It as Seeder,ue as SingleStoreDriver,tt as SingleTableManager,cn as SingleTablePatterns,rt as SingleTableQueryBuilder,nt as SingleTableRepository,p as UTC_CLOCK_DEFAULT,de as VitessDriver,v as applySqliteBootstrapPragmas,Lt as auditSchemaDrift,sn as browserAuth,Ye as browserQuery,$e as buildDatabaseSchema,Ce as buildDynamoDBMigrationPlan,H as buildMigrationPlan,lt as buildSchemaMeta,z as cacheClear,X as cacheConfig,Y as cacheStats,Ke as canonicalStorageType,Fe as canonicalizeDefault,Se as checkSchema,Et as clearLocalModels,Qt as clearModelRegistry,xe as clearQueryCache,e as config,en as configureBrowser,wt as configureModels,Dn as configureOrm,Ue as convertSchemaToDefinition,rn as createBrowserDb,Ie as createBrowserModel,E as createClient,qt as createDynamo,ln as createDynamoDBClient,c as createDynamoDBDriver,on as createDynamoDBItemBuilder,an as createDynamoDBQueryBuilder,hn as createDynamoDBToolingAdapter,$t as createFakerCompatLayer,Ve as createMigrationDriver,Ct as createModel,i as createQueryBuilder,st as createRepository,it as createSingleTableManager,xn as createTableFromModel,_ as dbInfo,I as dbOptimize,re as dbStats,L as dbWipe,Qe as defaultConfig,zt as defineConfig,Gt as defineModel,Tn as defineModels,wn as defineSeeder,ne as dumpDatabase,jt as dynamo,bt as escapeStringLiteral,C as executeMigration,ie as explain,q as explainAllQueries,ee as exportData,xt as extractChanges,vt as extractInsertId,We as extractModelSchema,ke as extractTableDefinition,ht as familyOfDeclared,gt as familyOfSqlType,se as file,Kt as formatSchemaDrift,be as freshDatabase,gn as generateAccessPatterns,W as generateDiagram,je as generateDiffOperations,_t as generateDiffSql,bn as generateDiffSqlString,T as generateMigration,Ze as generateModelSource,Ee as generateSql,yn as generateSqlString,Ut as getAllModels,tn as getBrowserConfig,P as getConfig,En as getDatabase,m as getDialectDriver,Wt as getModel,Vt as getModelRegistry,t as getPlaceholder,s as getPlaceholders,Ht as hasModel,mt as hashMigrationPlan,x as hashTableDefinition,te as importData,Zt as inflectSingular,K as inspectTable,oe as introspect,k as introspectDatabase,nn as isBrowser,St as isDefinitionEqual,dt as isGeneratedMigrationSql,Ot as isLosslessTypeChange,n as isMysqlLike,Sn as iterateAllPivots,ct as lastCreatedMigrationFiles,u as loadModels,le as makeModel,ye as makeSeeder,fn as marshallObject,me as migrateGenerate,ge as migrateList,Dt as migrateModels,he as migrateRollback,F as migrateStatus,ft as migrationBody,Le as modelNameForTable,j as modelShow,I as optimizeDatabase,Pt as parseStacksModels,pe as ping,q as queryExplainAll,l as quoteColumnForDialect,Ft as raw,Jt as registerBrowserModels,Rt as registerModel,W as relationDiagram,$n as releaseOrm,Yt as resetConnection,R as resetDatabase,B as resolveDialect,at as resolveKeyPattern,D as resolvePivot,Mt as resolveSqlitePragmas,J as runBenchmark,U as runSeeder,A as runSeeders,pt as satisfies,et as saveMigrationSnapshot,vn as seedModel,Ne as setConfig,ve as setQueryCacheMaxSize,j as showModel,f as singularizerFor,Te as sql,Xe as sqlTypeToAttr,pn as stacksModelToEntity,O as startConsole,Xt as stripTrailingS,ae as tableInfo,b as tableNameFor,yt as temporalLiteral,Z as tinker,Je as toDialectPlaceholders,un as toDynamoDBItem,dn as toModelInstance,Pe as toTableName,mn as unmarshallItem,we as unsafe,V as validateSchema,De as waitReady,L as wipeDatabase};
|
package/dist/type-inference.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { ValidationType } from './schema';
|
|
|
5
5
|
declare interface InferablePivotColumnAttribute {
|
|
6
6
|
default?: unknown
|
|
7
7
|
nullable?: boolean
|
|
8
|
+
required?: boolean
|
|
8
9
|
validation?: { rule: ValidationType; message?: Record<string, string> }
|
|
9
10
|
}
|
|
10
11
|
/** Minimal attribute definition for type inference */
|
|
@@ -15,6 +16,7 @@ declare interface InferableAttribute<T = unknown> {
|
|
|
15
16
|
hidden?: boolean
|
|
16
17
|
guarded?: boolean
|
|
17
18
|
nullable?: boolean
|
|
19
|
+
required?: boolean
|
|
18
20
|
default?: InferType<T>
|
|
19
21
|
validation?: {
|
|
20
22
|
rule: ValidationType
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bun-query-builder",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.3",
|
|
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",
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
"dependencies": {
|
|
84
84
|
"@stacksjs/clapp": "^0.2.16",
|
|
85
85
|
"@stacksjs/ts-faker": "^0.1.8",
|
|
86
|
-
"@stacksjs/ts-validation": "^0.5.
|
|
86
|
+
"@stacksjs/ts-validation": "^0.5.6",
|
|
87
87
|
"dynamodb-tooling": "^0.3.6"
|
|
88
88
|
},
|
|
89
89
|
"devDependencies": {
|
package/dist/chunk-cxpaxq2p.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ie}from"./chunk-4cs1xx1d.js";import{n,e,v,y,Pe,f,S,o,Je,Bt}from"./chunk-hjgcemhy.js";import{Database as ye}from"bun:sqlite";function M(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function pe(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 Ae(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}function J(t){if(typeof t==="number")return{length:t};return t}function ce(t){if(typeof t==="number")return{max:t};return t}function Be(t){return typeof t==="function"}function Le(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function be(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function V(t,r={}){if(!t)return r;return new Proxy(t,{get(s,i){if(i in r)return r[i];let a=s[i];if(a!==void 0)return a;let l=s[Le(i)];if(Be(l))return l.bind(s);return}})}function $t(t){let r=(d)=>{let g=Array.isArray(d)?d:[],D=Math.floor(Math.random()*g.length);return g[D]},s=()=>t.string,i=()=>t.number,a=()=>t.random,l=V(t.string,{alpha:(d)=>s()?.alpha?.(J(d)),alphanumeric:(d)=>s()?.alphanumeric?.(J(d)),numeric:(d)=>s()?.numeric?.(J(d)),sample:(d)=>s()?.sample?.(J(d)),hexadecimal:(d)=>s()?.hexadecimal?.(J(d))}),c=V(t.number,{int:(d)=>i()?.int?.(ce(d)),float:(d)=>{let g=ce(d);return be(Number(i()?.float?.(g)??0),g)}}),u=V(t.helpers,{arrayElement:r,arrayElements:(d,g)=>{let D=[...Array.isArray(d)?d:[]],k=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*D.length));for(let R=D.length-1;R>0;R-=1){let x=Math.floor(Math.random()*(R+1));[D[R],D[x]]=[D[x],D[R]]}return D.slice(0,Math.min(k,D.length))},shuffle:(d)=>{let g=[...Array.isArray(d)?d:[]];for(let D=g.length-1;D>0;D-=1){let k=Math.floor(Math.random()*(D+1));[g[D],g[k]]=[g[k],g[D]]}return g},maybe:(d,g)=>{let D=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<D?d():void 0},slugify:(d)=>String(d??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),p={string:l,number:c,helpers:u,datatype:{boolean:(d)=>{let g=typeof d==="number"?d:d?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(a()?.boolean?.())},number:(d)=>Number(i()?.int?.(ce(d))??0),float:(d)=>be(Number(i()?.float?.(d)??0),d),uuid:()=>crypto.randomUUID(),string:(d)=>String(s()?.alphanumeric?.({length:d??10})??""),hexadecimal:(d)=>String(s()?.hexadecimal?.(J(d))??""),array:(d)=>Array.from({length:d??3},()=>s()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:s()?.alphanumeric?.({length:8})})},location:V(t.address),address:V(t.address),vehicle:V(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:V(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(d,g){if(g in p)return p[g];let D=d[g];if(D&&typeof D==="object")return V(D);return D}})}function Me(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 N(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Me).filter((s)=>s!==null)}function G(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Ee=/^[A-Z_][A-Z0-9_]*$/i;function q(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(!Ee.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Ne(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 s=t.split(".");if(s.length>2||s.some((i)=>i.length===0||i.length>64||!Ee.test(i)))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 we(t,r){if(r.length!==1)return r;let s=r[0];if(Array.isArray(s))return[...s];if(s===void 0&&Bt(t)===0)return[];return r}var se=null,Te=new Map;function je(t,r){Te.set(t,r),te.clear()}function Et(){Te.clear(),te.clear()}function O(t){if(!se)try{se=import.meta.require("./chunk-hgsjz3vz.js").getModel}catch{se=()=>{return}}return se(t)??Te.get(t)}var ie=new Map,Fe=500;function De(t){let r=ie.get(t);if(r!==void 0)return r;let s=Je(t,"postgres");if(ie.size>=Fe)ie.clear();return ie.set(t,s),s}function xt(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 vt(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 ge{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 s=this.sqliteDb.run(t,r);return Promise.resolve({changes:s.changes,lastInsertId:s.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class $e{dialect;constructor(t){this.dialect=t}conn(){return y()}text(t){return this.dialect==="postgres"?De(t):t}async all(t,r){let s=await this.conn().unsafe(this.text(t),r);return Array.isArray(s)?s:[]}async get(t,r){let s=await this.conn().unsafe(this.text(t),r);if(Array.isArray(s))return s[0]??void 0;return s??void 0}async run(t,r){let s=await this.conn().unsafe(this.text(t),r);return{changes:xt(s),lastInsertId:vt(s)}}async insert(t,r,s){if(this.dialect==="postgres"){let l=await this.conn().unsafe(`${De(t)} RETURNING ${s}`,r),c=Array.isArray(l)?l[0]:l;return{changes:1,lastInsertId:c?c[s]??null:null}}let i=await this.conn().unsafe(t,r),a=vt(i);if(a==null){let l=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);a=(Array.isArray(l)?l[0]:l)?.id??null}return{changes:xt(i)||1,lastInsertId:a}}}var H=null,de=!1,W=null,ee=null,ae=null,le=null;function Dn(t){if(t.database instanceof ye)H=t.database,de=!1;else H=new ye(t.database||":memory:",{create:!0}),de=!0,v(H);W=null,ee=null}function $n(){let t=de,r=H;if(H=null,de=!1,W=null,ee=null,ae=null,le=null,t&&r)try{r.close()}catch{}}var ke=!1;function A(){if(H){if(!W||ee!==H)W=new ge(H),ee=H,ae="sqlite",le=null;return W}let t=e.dialect,r=e.database?.database??null;if(W&&ee===null&&ae===t&&le===r)return W;if(ee=null,ae=t,le=r,t==="sqlite"){if(!r&&!ke)ke=!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 ye(r||":memory:",{create:!0});v(s),W=new ge(s)}else W=new $e(t);return W}function En(){let t=A();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 We=30000,B="deleted_at",Re=500,he="__btm_rel__";function Z(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Y(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ke=new WeakMap;function Ue(t){let r=Ke.get(t);if(r)return r;let s=new Set,i=t.belongsToMany;if(i){if(Array.isArray(i)){for(let a of i)if(typeof a==="string")s.add(a.toLowerCase());else if(a&&typeof a==="object"&&a.model)s.add(a.model.toLowerCase())}else if(typeof i==="object")for(let a of Object.keys(i))s.add(a)}return Ke.set(t,s),s}function Ce(t){let r={};for(let[s,i]of Object.entries(t))r[E(s)]=i;return r}function qe(t){for(let r in t)if(E(r)!==r)return Ce(t);return t}function He(t,r){if(t[r])return t[r];let s=E(r);if(t[s])return t[s];for(let i of Object.keys(t))if(E(i)===s)return t[i];return}class C{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,s){this._definition=t,this._exists=s,this._attributes=qe({...r}),this._original=null;let i=Ue(t);if(i.size===0)return;let a=this;return new Proxy(this,{get(l,c,u){if(typeof c==="string"&&i.has(c)&&!(c in l))return()=>{let m=Se(t,c);if(!m||m.type!=="belongsToMany")throw Error(`[orm] relation '${c}' did not resolve to a belongsToMany on '${t.name}'`);let p=O(m.relatedModelName),d=p?.getDefinition?.()||p?.definition;if(!d)throw Error(`[orm] related model '${m.relatedModelName}' is not registered`);return new kt(a,t,m,d)};return Reflect.get(l,c,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 s=r(this._attributes);if(s!==void 0)return s}catch{}return this._attributes[E(t)]}getAttribute(t){return this._attributes[E(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[E(t)]=r}only(t){let r={};for(let s of t)r[s]=this._attributes[E(s)];return r}except(t){let r=new Set(t.map((i)=>E(i))),s={};for(let i of Object.keys(this._attributes))if(!r.has(i))s[i]=this._attributes[i];return s}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=E(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()[E(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[s,i]of Object.entries(t)){let a=He(r,s),l=!a&&E(s).endsWith("_id");if(a?.fillable&&!a?.guarded||l){if(this._original===null)this._original={...this._attributes};this._attributes[E(s)]=i}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Ce(t);Object.assign(this._attributes,r);for(let s of Object.keys(r))this._forced.add(s);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,s=this._definition.attributes,i={};for(let[u,m]of Object.entries(s)){if(m.guarded&&!this._forced.has(E(u)))continue;let p=E(u);if(this._attributes[p]!==void 0)i[p]=this._attributes[p]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in i))i[u]=this._attributes[u];let a=this._attributes[t],c=s[t]?.guarded&&!this._forced.has(t);if(a!=null&&!(t in i)&&!c)i[t]=a;if(Y(this._definition)){let u=G(),m=this._attributes.created_at;i.created_at=m===void 0||m===null?u:m,i.updated_at=u}if(this._definition.traits?.useUuid&&!i.uuid)i.uuid=crypto.randomUUID();return await r?.beforeCreate?.(i),i}async _markInserted(t,r){let s=this._definition.primaryKey||"id";for(let[i,a]of Object.entries(t))this._attributes[i]=a;if(!(s in t)&&r!=null)this._attributes[s]=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,s]of Object.entries(t))if(this.isDirty(r))this._attributes[E(r)]=s(this._attributes)}async save(){let t=A(),r=this._definition.primaryKey||"id",s=this._definition.hooks;if(this._exists){this._applySetters(),await s?.beforeUpdate?.(this,this.getChanges());let i=this.getChanges(),a=Object.keys(i);if(a.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let l=a.map((u)=>`${u} = ?`).join(", "),c=[...Object.values(i),this._attributes[r]];if(Y(this._definition)){let u=G();await t.run(`UPDATE ${this._definition.table} SET ${l}, updated_at = ? WHERE ${r} = ?`,[...Object.values(i),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${l} WHERE ${r} = ?`,c)}await s?.afterUpdate?.(this)}else{let i=await this._prepareInsert(),a=Object.keys(i),l=a.map(()=>"?").join(", "),c=await t.insert(`INSERT INTO ${this._definition.table} (${a.join(", ")}) VALUES (${l})`,Object.values(i),r);return await this._markInserted(i,r in i?void 0:c.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=A(),r=this._definition.primaryKey||"id",s=this._attributes[r];if(s==null)return null;let i=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[s]);if(!i)return null;return new C(this._definition,i,!0)}async delete(){let t=A(),r=this._definition.primaryKey||"id",s=this._attributes[r],i=this._definition.hooks;if(s==null)throw Error("Cannot delete a model without a primary key");if(await i?.beforeDelete?.(this),Z(this._definition)){let a=G();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[a,s]),this._attributes[B]=a}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[s]);return await i?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],s=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await s?.beforeDelete?.(this),await A().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await s?.afterDelete?.(this),!0}async restore(){if(!Z(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 A().run(`UPDATE ${this._definition.table} SET ${B} = ? WHERE ${t} = ?`,[null,r]),this._attributes[B]=null,this._original=null,this}trashed(){return this._attributes[B]!=null}async refresh(){let t=A(),r=this._definition.primaryKey||"id",s=this._attributes[r];if(!s)throw Error("Cannot refresh a model without a primary key");let i=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[s]);if(!i)return null;return this._attributes=i,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 C(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,s]of Object.entries(this._relations))if(Array.isArray(s))t[r]=s.map((i)=>i.toArray());else if(s)t[r]=s.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[s,i]of Object.entries(this._definition.attributes))if(i.hidden)t.add(s);let r={};for(let[s,i]of Object.entries(this._attributes))if(!t.has(s))r[s]=i;for(let[s,i]of Object.entries(this._relations))if(Array.isArray(i))r[s]=i.map((a)=>a.toJSON());else if(i)r[s]=i.toJSON();else r[s]=null;return r}}var _e=new Map,xe=new Map,te=new Map,Qe=1000;function F(t){return E(t)}function E(t){let r=_e.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),_e.set(t,r),r}function z(t){let r=xe.get(t);if(r!==void 0)return r;return r=Pe(t),xe.set(t,r),r}var ue=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ve=[...ue,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function ve(t,r){let s=t[r];if(!s)return[];if(Array.isArray(s))return s.map((i)=>typeof i==="string"?i:String(i?.model??"")).filter(Boolean);if(typeof s==="object")return Object.keys(s);if(typeof s==="string")return[s];return[]}function ze(t,r){let s=t.name??t.table??"model",a=Ve.filter((c)=>ve(t,c).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((c)=>!ue.includes(c));if(a.length>0)return`[orm] '${s}' declares '${r}' as ${a.join("/")}, which eager loading does not support yet. Supported kinds: ${ue.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let l=ue.flatMap((c)=>ve(t,c));return l.length>0?`[orm] '${s}' has no relation '${r}'. Available: ${l.join(", ")}.`:`[orm] '${s}' has no relation '${r}' \u2014 it declares no relations at all.`}function Se(t,r){let{name:s,table:i}=t,a=t.primaryKey||"id";function l(b){if(!b)return null;if(Array.isArray(b)){for(let T of b){let K=typeof T==="string"?T:T?.model||"";if(K&&K.toLowerCase()===r.toLowerCase())return K}return null}if(typeof b==="object"){for(let[T,K]of Object.entries(b))if(T===r||T.toLowerCase()===r.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||T}return null}function c(){let b=t.belongsTo;if(!b)return null;let T=r.toLowerCase(),K=(h)=>{if(typeof h==="string")return{model:h};if(h&&typeof h==="object"&&typeof h.model==="string")return{model:h.model,foreignKey:h.foreignKey};return null};if(Array.isArray(b)){for(let h of b){let w=K(h);if(w&&w.model.toLowerCase()===T)return w}return null}if(typeof b==="object"){for(let[h,w]of Object.entries(b))if(h===r||h.toLowerCase()===T)return K(w)}return null}function u(){let b=t.belongsToMany;if(!b)return null;if(Array.isArray(b)){for(let T of b)if(typeof T==="string"){if(T.toLowerCase()===r.toLowerCase())return{entry:T}}else if(T&&typeof T==="object"&&T.model){if(T.model.toLowerCase()===r.toLowerCase())return{entry:T}}return null}if(typeof b==="object"){for(let[T,K]of Object.entries(b))if(T===r||T.toLowerCase()===r.toLowerCase())return{entry:K}}return null}function m(b){let T=t[b];if(!T)return null;let K=r.toLowerCase();if(Array.isArray(T)){for(let h of T){let w=typeof h==="string"?h:String(h?.model??"");if(!w||w.toLowerCase()!==K)continue;let I=typeof h==="object"?h?.morphName:void 0;return{model:w,morphName:String(I??`${E(s)}able`)}}return null}if(typeof T==="object")for(let[h,w]of Object.entries(T)){let I=typeof w==="string"?w:String(w?.model??"");if(h.toLowerCase()!==K&&I.toLowerCase()!==K)continue;let L=typeof w==="object"?w?.morphName:void 0;return{model:I,morphName:String(L??h)}}return null}for(let b of["morphMany","morphOne"]){let T=m(b);if(!T)continue;let h=O(T.model)?.getTable?.()||z(T.model);return{type:b,relatedModelName:T.model,relatedTable:h,foreignKey:`${T.morphName}_id`,localKey:a,morphTypeColumn:`${T.morphName}_type`,morphTypeValue:i}}let p=l(t.hasMany);if(p){let T=O(p)?.getTable?.()||z(p),K=E(s)+"_id";return{type:"hasMany",relatedModelName:p,relatedTable:T,foreignKey:K,localKey:a}}let d=l(t.hasOne);if(d){let T=O(d)?.getTable?.()||z(d),K=E(s)+"_id";return{type:"hasOne",relatedModelName:d,relatedTable:T,foreignKey:K,localKey:a}}let g=c();if(g){let b=g.model,T=O(b),K=T?.getTable?.()||z(b),h=T?.getDefinition?.()?.primaryKey||"id",w=g.foreignKey||`${E(b)}_id`;return{type:"belongsTo",relatedModelName:b,relatedTable:K,foreignKey:w,localKey:h}}let D=u();if(D){let b=typeof D.entry==="object",T=b?D.entry.model:D.entry,h=O(T)?.getTable?.()||z(T),w=b?D.entry:null,I,L;if(w?.table)I=w.table;else if(w?.through){L=w.through;let P=O(w.through);if(!P)throw Error(`[orm] belongsToMany relation '${r}' on '${s}' references unknown through model '${w.through}'. Make sure '${w.through}' is registered.`);I=P.getTable?.()||P.getDefinition?.()?.table||z(w.through)}else{let P=oe(i),U=oe(h);I=[P,U].sort().join("_")}let j=w?.foreignKey||`${oe(i)}_id`,X=w?.relatedKey||`${oe(h)}_id`,Q=[];if(w?.pivot?.columns)for(let P of Object.keys(w.pivot.columns))Q.push(P);if(L){let P=O(L),U=P?.getDefinition?.()||P?.definition,fe=U?.attributes??{},Oe=U?.primaryKey??"id";for(let re of Object.keys(fe)){if(re===j||re===X||re===Oe)continue;if(!Q.includes(re))Q.push(re)}}return{type:"belongsToMany",relatedModelName:T,relatedTable:h,foreignKey:j,localKey:a,pivotTable:I,pivotFkParent:j,pivotFkRelated:X,pivotColumns:Q,pivotModelName:L,pivotTimestamps:Boolean(w?.pivot?.timestamps)}}let k=(b,T)=>{if(!b||typeof b!=="object"||Array.isArray(b))return null;let K=b[r]??b[Object.keys(b).find((U)=>U.toLowerCase()===r.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:h,target:w}=K;if(!h||!w)return null;let I=O(h),L=I?.getDefinition?.()||I?.definition,j=I?.getTable?.()||L?.table||z(h),X=L?.primaryKey||"id",P=O(w)?.getTable?.()||z(w);return{type:T,relatedModelName:w,relatedTable:P,foreignKey:`${E(s)}_id`,localKey:a,throughTable:j,throughForeignKey:`${E(s)}_id`,throughLocalKey:X,targetForeignKey:`${oe(j)}_id`}},R=k(t.hasManyThrough,"hasManyThrough");if(R)return R;let x=k(t.hasOneThrough,"hasOneThrough");if(x)return x;return null}function me(t,r){let s=new Set;for(let i of t){let a=i.get(r);if(a!=null)s.add(a)}return[...s]}function oe(t){return f(e.relations?.singularizeStrategy)(t)}class kt{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,s,i){this._parent=t,this._parentDef=r,this._resolved=s,this._relatedDef=i}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,s){if(s===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[s]});return this}wherePivot(t,r,s){if(s===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[s]});return this}wherePivotIn(t,r){if(!r.length)return this;let s=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${s})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let s=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${s})`,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(Ne(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=[],s=`SELECT ${this.relatedSelectColumns().map((i)=>`${this.relatedTable}.${i} AS ${he}${i}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;s+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,s+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let i of this._pivotWheres)s+=` AND ${i.sql}`,t.push(...i.params);for(let i of this._wheres)s+=` AND ${i.sql}`,t.push(...i.params);if(this._orderBy.length>0)s+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)s+=` LIMIT ${this._limit}`;if(this._offset!==void 0)s+=` OFFSET ${this._offset}`;return{sql:s,params:t}}hydrateRows(t){let r=this.fkParent,s=this.fkRelated;return t.map((i)=>{let a={},l={};for(let[u,m]of Object.entries(i))if(u.startsWith(he))a[u.slice(he.length)]=m;else if(u!==r&&u!==s)l[u]=m;let c=new C(this._relatedDef,a,!0);return c.pivot=l,c})}async get(){let t=A(),{sql:r,params:s}=this.buildSelect(),i=await t.all(r,s);return this.hydrateRows(i)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=A(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];for(let a of this._pivotWheres)r+=` AND ${a.sql}`,s.push(...a.params);let i=await t.get(r,s);return Number(i?.count??0)}async exists(){return await this.count()>0}now(){return G()}async attach(t,r={}){let s=A(),i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=this._resolved.pivotTimestamps?this.now():null,l=0;for(let c of i){let u={[this.fkParent]:this.parentId,[this.fkRelated]:c,...r};if(a){if(u.created_at===void 0)u.created_at=a;if(u.updated_at===void 0)u.updated_at=a}let m=Object.keys(u),p=m.map(()=>"?").join(", "),d=`INSERT INTO ${this.pivotTable} (${m.join(", ")}) VALUES (${p})`,g=m.map((D)=>u[D]);await s.run(d,g),l++}return l}async detach(t){let r=A(),s=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,i=[this.parentId];if(t!==void 0&&t!==null){let a=Array.isArray(t)?t:[t];if(a.length===0)return 0;let l=a.map(()=>"?").join(", ");s+=` AND ${this.fkRelated} IN (${l})`,i.push(...a)}return(await r.run(s,i)).changes}async updateExistingPivot(t,r){let s=A(),i={...r};if(this._resolved.pivotTimestamps&&i.updated_at===void 0)i.updated_at=this.now();let a=Object.keys(i);if(a.length===0)return 0;let l=a.map((m)=>`${m} = ?`).join(", "),c=`UPDATE ${this.pivotTable} SET ${l} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...a.map((m)=>i[m]),this.parentId,t];return(await s.run(c,u)).changes}async sync(t){let r=A(),s=new Map;for(let p of t)if(p!=null&&typeof p==="object"&&"id"in p){let{id:d,...g}=p;s.set(d,g)}else s.set(p,{});let i=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),a=new Set(i.map((p)=>p[this.fkRelated])),l=[],c=[],u=[],m=[...a].filter((p)=>!s.has(p));if(m.length>0)await this.detach(m),c.push(...m);for(let[p,d]of s)if(!a.has(p))await this.attach(p,d),l.push(p);else if(Object.keys(d).length>0)await this.updateExistingPivot(p,d),u.push(p);return{attached:l,detached:c,updated:u}}async toggle(t){let r=A(),s=Array.isArray(t)?t:[t];if(s.length===0)return{attached:[],detached:[]};let i=s.map(()=>"?").join(", "),a=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${i})`,[this.parentId,...s]),l=new Set(a.map((m)=>m[this.fkRelated])),c=s.filter((m)=>!l.has(m)),u=s.filter((m)=>l.has(m));if(c.length>0)await this.attach(c);if(u.length>0)await this.detach(u);return{attached:c,detached:u}}}class _{_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,s){if(s===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:s,boolean:"and"});return this}orWhere(t,r,s){if(s===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:s,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 q(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return q(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return q(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return q(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:we(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:we(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let s=new _(this._definition);if(r(s),s._wheres.length===0)return this;let i=[],a=s.buildWhereClauses(i);if(!a)return this;return this._wheres.push({raw:`(${a})`,rawParams:i,boolean:t}),this}whereBetween(t,r){return q(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){q(t,"whereNotBetween(column)");let s=F(t);return this._wheres.push({raw:`(${s} < ? OR ${s} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Ne(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 s of this._wheres){let i;if(s.raw){if(i=s.raw,s.rawParams&&s.rawParams.length>0)t.push(...s.rawParams)}else if(s.value===null){let a=F(s.column);i=s.operator==="="?`${a} IS NULL`:`${a} IS NOT NULL`}else if(s.operator==="in"||s.operator==="not in"){let a=s.value;i=o(F(s.column),a,s.operator==="not in",a.map(()=>"?").join(", ")),t.push(...a)}else i=`${F(s.column)} ${s.operator} ?`,t.push(s.value);r.push({conn:s.boolean==="or"?"OR":"AND",sql:i})}return S(r)}softDeleteClause(){if(this._trashed==="include"||!Z(this._definition))return"";return this._trashed==="only"?`${B} IS NOT NULL`:`${B} 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):"",s=this.softDeleteClause();if(r&&s)return`(${r}) AND ${s}`;return r||s}buildQuery(){let t=[],s=`SELECT ${this._select.map((a)=>a==="*"?a:F(a)).join(", ")} FROM ${this._definition.table}`,i=this.composeWhere(t);if(i)s+=` WHERE ${i}`;if(this._orderBy.length>0)s+=` ORDER BY ${this._orderBy.map((a)=>`${F(a.column)} ${a.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)s+=` LIMIT ${this._limit}`;if(this._offset!==void 0)s+=` OFFSET ${this._offset}`;return{sql:s,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 s=A(),i=this._definition.primaryKey||"id",a=`${this._definition.name}:${t}`,l=te.get(a);if(l===void 0){if(l=Se(this._definition,t),te.size>=Qe)te.clear();te.set(a,l)}if(!l)throw Error(ze(this._definition,t));let c=l.type==="hasOne"||l.type==="morphOne";if(l.type==="hasMany"||l.type==="hasOne"||l.type==="morphMany"||l.type==="morphOne"){let u=me(r,i);if(u.length===0)return;let m=u.map(()=>"?").join(", "),p=l.morphTypeColumn?` AND ${l.morphTypeColumn} = ?`:"",d=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${l.foreignKey} IN (${m})${p}`,l.morphTypeColumn?[...u,l.morphTypeValue]:u),g=O(l.relatedModelName),D=g?.getDefinition?.()||g?.definition||this._definition;if(!c){let k=new Map;for(let R of d){let x=R[l.foreignKey];if(!k.has(x))k.set(x,[]);k.get(x).push(R)}for(let R of r){let x=k.get(R.get(i))||[];R.setRelation(t,x.map((b)=>new C(D,b,!0)))}}else{let k=new Map;for(let R of d){let x=R[l.foreignKey];if(!k.has(x))k.set(x,R)}for(let R of r){let x=k.get(R.get(i));R.setRelation(t,x?new C(D,x,!0):null)}}}if(l.type==="belongsTo"){let u=new Set;for(let R of r){let x=R._attributes[l.foreignKey];if(x!=null)u.add(x)}let m=[...u];if(m.length===0)return;let p=m.map(()=>"?").join(", "),d=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${l.localKey} IN (${p})`,m),g=O(l.relatedModelName),D=g?.getDefinition?.()||g?.definition||this._definition,k=new Map;for(let R of d)k.set(R[l.localKey],R);for(let R of r){let x=R._attributes[l.foreignKey],b=k.get(x);R.setRelation(t,b?new C(D,b,!0):null)}}if(l.type==="belongsToMany"){let u=me(r,i);if(u.length===0)return;if(!l.pivotTable||!l.pivotFkParent||!l.pivotFkRelated)return;let m=u.map(()=>"?").join(", "),p=await s.all(`SELECT * FROM ${l.pivotTable} WHERE ${l.pivotFkParent} IN (${m})`,u);if(p.length===0){for(let h of r)h.setRelation(t,[]);return}let d=new Set;for(let h of p){let w=h[l.pivotFkRelated];if(w!=null)d.add(w)}let g=[...d],D=O(l.relatedModelName),k=D?.getDefinition?.()||D?.definition||this._definition,R=k?.primaryKey||"id",x=[];if(g.length>0){let h=g.map(()=>"?").join(", ");x=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${R} IN (${h})`,g)}let b=new Map;for(let h of x)b.set(h[R],h);let T=new Map;for(let h of p){let w=h[l.pivotFkParent];if(!T.has(w))T.set(w,[]);T.get(w).push(h)}let K=new Set([l.pivotFkParent,l.pivotFkRelated]);for(let h of r){let w=h.get(i),L=(T.get(w)||[]).map((j)=>{let X=b.get(j[l.pivotFkRelated]);if(!X)return null;let Q=new C(k,X,!0),P={};for(let[U,fe]of Object.entries(j))if(!K.has(U))P[U]=fe;return Q.pivot=P,Q}).filter((j)=>j!==null);h.setRelation(t,L)}}if(l.type==="hasManyThrough"||l.type==="hasOneThrough"){let u=me(r,i);if(u.length===0)return;let m=l.throughLocalKey||"id",p=u.map(()=>"?").join(", "),d=await s.all(`SELECT ${m}, ${l.throughForeignKey} FROM ${l.throughTable} WHERE ${l.throughForeignKey} IN (${p})`,u);if(d.length===0){for(let K of r)K.setRelation(t,l.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let K of d)g.set(K[m],K[l.throughForeignKey]);let D=[...new Set(d.map((K)=>K[m]))],k=D.map(()=>"?").join(", "),R=await s.all(`SELECT * FROM ${l.relatedTable} WHERE ${l.targetForeignKey} IN (${k})`,D),x=O(l.relatedModelName),b=x?.getDefinition?.()||x?.definition||this._definition,T=new Map;for(let K of R){let h=g.get(K[l.targetForeignKey]);if(h==null)continue;if(!T.has(h))T.set(h,[]);T.get(h).push(new C(b,K,!0))}for(let K of r){let h=T.get(K.get(i))||[];K.setRelation(t,l.type==="hasManyThrough"?h:h[0]??null)}}}async get(){let t=A(),{sql:r,params:s}=this.buildQuery(),a=(await t.all(r,s)).map((l)=>new C(this._definition,l,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(a);return a}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=A(),r=[],s=`SELECT COUNT(*) as count FROM ${this._definition.table}`,i=this.composeWhere(r);if(i)s+=` WHERE ${i}`;let a=await t.get(s,r);return Number(a?.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){q(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let s=A(),i=[r],a=F(t),l=`UPDATE ${this._definition.table} SET ${a} = ${a} + ?`;if(Y(this._definition))l+=", updated_at = ?",i.push(G());let c=this.composeWhere(i);if(c)l+=` WHERE ${c}`;return(await s.run(l,i)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let s=0;while(!0){let i=new _(this._definition);i._wheres=[...this._wheres],i._orderBy=[...this._orderBy],i._select=[...this._select],i._withRelations=[...this._withRelations],i._trashed=this._trashed,i._limit=t,i._offset=s*t;let a=await i.get();if(a.length===0)break;if(await r(a)===!1)break;if(a.length<t)break;s++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let l=t;r=l.perPage??15,t=l.page??1}let s=await this.count(),i=Math.ceil(s/r);this._limit=r,this._offset=(t-1)*r;let a=await this.get();return{data:a,total:s,page:t,perPage:r,lastPage:i,hasMorePages:t<i,isEmpty:a.length===0,from:a.length>0?(t-1)*r+1:null,to:a.length>0?(t-1)*r+a.length:null,meta:{perPage:r,page:t,total:s,lastPage:i}}}async pluck(t){q(t,"pluck(column)");let r=A(),s=[],i=F(t),a=`SELECT ${i} FROM ${this._definition.table}`,l=this.composeWhere(s);if(l)a+=` WHERE ${l}`;if(this._orderBy.length>0)a+=` ORDER BY ${this._orderBy.map((u)=>`${F(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)a+=` LIMIT ${this._limit}`;if(this._offset!==void 0)a+=` OFFSET ${this._offset}`;return(await r.all(a,s)).map((u)=>u[i])}async aggregate(t,r){q(r,`${t}(column)`);let s=A(),i=[],a=`SELECT ${t}(${F(r)}) as v FROM ${this._definition.table}`,l=this.composeWhere(i);if(l)a+=` WHERE ${l}`;let u=(await s.get(a,i))?.v;if(u==null)return null;if(typeof u==="string"){let m=Number(u);return u.trim()!==""&&!Number.isNaN(m)?m: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=Z(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=A(),s=this._definition.table,i=this._definition.hooks,a=[],l=this.composeWhere(a);if(t&&this._trashed==="include")l=l?`(${l}) AND ${B} IS NULL`:`${B} IS NULL`;let c=l?` WHERE ${l}`:"",u=t?G():void 0;if(!i?.beforeDelete&&!i?.afterDelete)return t?(await r.run(`UPDATE ${s} SET ${B} = ?${c}`,[u,...a])).changes:(await r.run(`DELETE FROM ${s}${c}`,a)).changes;let m=this._definition.primaryKey||"id",d=(await r.all(`SELECT * FROM ${s}${c}`,a)).map((k)=>new C(this._definition,k,!0)),g=d.map((k)=>k._attributes[m]);if(g.some((k)=>k==null))throw Error(`Cannot delete a model without a primary key: '${m}' is missing from a matching row`);for(let k of d)await i.beforeDelete?.(k);let D=0;for(let k=0;k<g.length;k+=Re){let R=g.slice(k,k+Re),x=`${m} IN (${R.map(()=>"?").join(", ")})`;D+=t?(await r.run(`UPDATE ${s} SET ${B} = ? WHERE ${x}`,[u,...R])).changes:(await r.run(`DELETE FROM ${s} WHERE ${x}`,R)).changes}for(let k of d){if(t)k._attributes[B]=u;await i.afterDelete?.(k)}return D}async update(t){this.assertNoUnappliedClauses("update");let r=A(),s=Object.entries(t),i=s.map(([u])=>`${F(u)} = ?`).join(", "),a=s.map(([,u])=>u);if(Y(this._definition))a.push(G());let l=`UPDATE ${this._definition.table} SET ${i}${Y(this._definition)?", updated_at = ?":""}`,c=this.composeWhere(a);if(c)l+=` WHERE ${c}`;return(await r.run(l,a)).changes}}function Ge(t){let r={query:()=>new _(t),where(s,i,a){return new _(t).where(s,i,a)},orWhere(s,i,a){return new _(t).orWhere(s,i,a)},whereIn(s,i){return new _(t).whereIn(s,i)},whereNotIn(s,i){return new _(t).whereNotIn(s,i)},whereNull(s){return new _(t).whereNull(s)},whereNotNull(s){return new _(t).whereNotNull(s)},whereLike(s,i){return new _(t).whereLike(s,i)},orderBy(s,i="asc"){return new _(t).orderBy(s,i)},orderByDesc(s){return new _(t).orderByDesc(s)},select(...s){return new _(t).select(...s)},with(...s){return new _(t).with(...s)},limit:(s)=>new _(t).limit(s),take:(s)=>new _(t).take(s),skip:(s)=>new _(t).skip(s),withTrashed:()=>new _(t).withTrashed(),onlyTrashed:()=>new _(t).onlyTrashed(),async find(s){let i=A(),a=t.primaryKey||"id",l=Z(t)?` AND ${B} IS NULL`:"",c=await i.get(`SELECT * FROM ${t.table} WHERE ${a} = ?${l}`,[s]);return c?new C(t,c,!0):void 0},async findOrFail(s){let i=await r.find(s);if(!i)throw Error(`${t.name} with id ${s} not found`);return i},async findMany(s){let i=A(),a=t.primaryKey||"id",l=Z(t)?` AND ${B} IS NULL`:"";return(await i.all(`SELECT * FROM ${t.table} WHERE ${a} IN (${s.map(()=>"?").join(", ")})${l}`,s)).map((u)=>new C(t,u,!0))},all:()=>new _(t).get(),first:()=>new _(t).first(),firstOrFail:()=>new _(t).firstOrFail(),last:()=>new _(t).last(),count:()=>new _(t).count(),exists:()=>new _(t).exists(),doesntExist:()=>new _(t).doesntExist(),paginate:(s,i)=>new _(t).paginate(s,i),whereBetween(s,i){return new _(t).whereBetween(s,i)},whereNotBetween(s,i){return new _(t).whereNotBetween(s,i)},async create(s){let i=new C(t,s,!1);return await i.save(),i},async createMany(s){let i=s.map((m)=>new C(t,m,!1));if(!i.length)return[];let a=A(),l=t.primaryKey||"id",c=[];for(let m of i)c.push(await m._prepareInsert());let u=new Map;c.forEach((m,p)=>{let d=Object.keys(m).join("\x00"),g=u.get(d);if(g)g.push(p);else u.set(d,[p])});for(let[m,p]of u){let d=m?m.split("\x00"):[],g=!d.includes(l);if(!d.length||g&&a.dialect==="mysql"){for(let k of p){let R=c[k],x=Object.keys(R),b=await a.insert(x.length?`INSERT INTO ${t.table} (${x.join(", ")}) VALUES (${x.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(R),l);await i[k]._markInserted(R,g?b.lastInsertId:void 0)}continue}let D=Math.max(1,Math.floor(We/d.length));for(let k=0;k<p.length;k+=D){let R=p.slice(k,k+D),x=`INSERT INTO ${t.table} (${d.join(", ")}) VALUES ${R.map(()=>`(${d.map(()=>"?").join(", ")})`).join(", ")}`,b=R.flatMap((h)=>d.map((w)=>c[h][w]));if(!g){await a.run(x,b);for(let h of R)await i[h]._markInserted(c[h]);continue}let T=(await a.all(`${x} RETURNING ${l}`,b)).map((h)=>h[l]),K=T.every((h)=>typeof h==="number"||typeof h==="bigint")?[...T].sort((h,w)=>h<w?-1:h>w?1:0):T;for(let h=0;h<R.length;h++)await i[R[h]]._markInserted(c[R[h]],K[h])}}return i},async updateOrCreate(s,i){let a=new _(t);for(let[c,u]of Object.entries(s))a=a.where(c,u);let l=await a.first();if(l)return await l.update(i),l;return this.create({...s,...i})},async firstOrCreate(s,i){let a=new _(t);for(let[c,u]of Object.entries(s))a=a.where(c,u);return await a.first()||this.create({...s,...i})},async update(s,i){let a=await r.findOrFail(s);return await a.update(i),a},async delete(s){let i=await r.find(s);return i?i.delete():!1},destroy(s){return r.delete(s)},async forceDelete(s){let i=await r.withTrashed().find(s);return i?i.forceDelete():!1},remove(s){return r.forceDelete(s)},async truncate(){await A().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(s={}){return new C(t,s,!1)},latest:(s="created_at")=>new _(t).orderByDesc(s),oldest:(s="created_at")=>new _(t).orderBy(s,"asc"),max:(s)=>new _(t).max(s),min:(s)=>new _(t).min(s),avg:(s)=>new _(t).avg(s),sum:(s)=>new _(t).sum(s),pluck(s){return new _(t).pluck(s)}};return new Proxy(r,{get(s,i){if(typeof i==="string"&&i.startsWith("where")&&i.length>5){let a=i.slice(5),l=a.charAt(0).toLowerCase()+a.slice(1);if(l in t.attributes||l==="id"||l===t.primaryKey)return(c)=>new _(t).where(l,c)}return Reflect.get(s,i)}})}function Ct(t){let r=Ge(t);if(t?.name)je(t.name,r);return r}async function xn(t){let r=A(),s=E(t.primaryKey||"id"),i=[],a=new Set([s]);if(i.push(t.autoIncrement!==!1?`${s} INTEGER PRIMARY KEY AUTOINCREMENT`:`${s} INTEGER PRIMARY KEY`),t.traits?.useUuid)i.push("uuid TEXT UNIQUE"),a.add("uuid");for(let[l,c]of Object.entries(t.attributes)){let u=E(l);if(a.has(u))continue;a.add(u);let m=pe(c.type),p=Ae(m);if(u.endsWith("_id")&&(m===void 0||M(m)))p="INTEGER";let d=`${u} ${p}`;if(c.unique)d+=" UNIQUE";if(typeof c.foreignKey==="object"&&c.foreignKey!==null){let g=c.foreignKey;if(d+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)d+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)d+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}i.push(d)}for(let l of N(t.belongsTo)){let c=l.foreignKey??`${E(l.model)}_id`;if(a.has(c))continue;a.add(c),i.push(`${c} INTEGER`)}if(Y(t))for(let l of["created_at","updated_at"]){if(a.has(l))continue;a.add(l),i.push(`${l} TEXT`)}if(Z(t)&&!a.has("deleted_at"))a.add("deleted_at"),i.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${i.join(", ")})`,[])}async function vn(t,r,s){let i=A(),a=t.traits?.useSeeder,l=r??(typeof a==="object"&&a?a.count:10);if(!s)try{let c=await import("./chunk-r2ta1rnj.js");s=$t(c.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let c=0;c<l;c++){let u={};for(let[p,d]of Object.entries(t.attributes))if(d.factory)u[E(p)]=d.factory(s);if(Y(t)){let p=G();u.created_at=p,u.updated_at=p}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let m=Object.keys(u);await i.run(`INSERT INTO ${t.table} (${m.join(", ")}) VALUES (${m.map(()=>"?").join(", ")})`,Object.values(u))}}var ne=new Map;function Wt(t){return ne.get(t)}function Ut(){return[...ne.values()]}function Vt(){return Object.fromEntries(ne)}function Ht(t){return ne.has(t)}function Qt(){ne.clear(),Et()}function Rt(t,r){return ne.set(t,r),r}function Xe(){return typeof window<"u"&&typeof document<"u"}function Gt(t){let r;if(Xe())r=Ie(t);else{let s=Ct(t);r=Object.assign(s,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return Rt(t.name,r),r}function Jt(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
|
|
3
|
-
export{M,Ae,$t,Me,N,Et,xt,vt,Dn,$n,En,kt,Ct,xn,vn,Wt,Ut,Vt,Ht,Qt,Rt,Gt,Jt};
|