@xwxfox/foxdb 0.0.1 → 0.1.0
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/LICENSE.md +20 -20
- package/README.md +275 -274
- package/dist/index.d.mts +810 -137
- package/dist/index.mjs +23 -19
- package/package.json +3 -2
package/dist/index.mjs
CHANGED
|
@@ -1,48 +1,52 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Database as
|
|
3
|
-
${
|
|
2
|
+
import{Database as Nt,constants as kt}from"bun:sqlite";class we{timers=new Set;timersByName=new Map;tasks=new Map;schedule(e,t,n){this.clear(e),this.tasks.set(e,n);let r=setInterval(()=>{try{n()}catch(s){console.error(`[foxdb] scheduler task "${e}" failed:`,s)}},t);this.timers.add(r),this.timersByName.set(e,r)}clear(e){let t=this.timersByName.get(e);if(t)clearInterval(t),this.timers.delete(t),this.timersByName.delete(e);this.tasks.delete(e)}clearAll(){for(let e of this.timers)clearInterval(e);this.timers.clear(),this.timersByName.clear(),this.tasks.clear()}}import{existsSync as Ct,unlinkSync as At}from"fs";class K{db;scheduler=new we;constructor(e={}){let t=e.path??":memory:";this.db=new Nt(t,{create:!0}),this.db.run("PRAGMA journal_mode = WAL;");let n=e.synchronous??"NORMAL",r=e.cacheSize??-64000,s=e.busyTimeout??5000,a=e.mmapSize??268435456;this.db.run(`PRAGMA synchronous = ${n};`),this.db.run(`PRAGMA cache_size = ${r};`),this.db.run(`PRAGMA busy_timeout = ${s};`),this.db.run(`PRAGMA mmap_size = ${a};`),this.db.run("PRAGMA foreign_keys = ON;"),this.db.run("PRAGMA temp_store = MEMORY;");let o=e.autoVacuum??!1;if(o)this.db.run(`PRAGMA auto_vacuum = ${o.toUpperCase()};`)}exec(e){this.db.run(e)}transaction(e){return this.db.transaction(e)()}close(){this.scheduler.clearAll();for(let e of this._stmtCache.values())try{e.finalize()}catch{}this._stmtCache.clear();try{this.db.fileControl(kt.SQLITE_FCNTL_PERSIST_WAL,0),this.db.run("PRAGMA wal_checkpoint(TRUNCATE);")}catch{}this.db.close()}static _MAX_CACHE_SIZE=256;_stmtCache=new Map;prepare(e){let t=this._stmtCache.get(e);if(!t){if(t=this.db.prepare(e),this._stmtCache.size>=K._MAX_CACHE_SIZE){let n=this._stmtCache.keys().next().value;if(n!==void 0){let r=this._stmtCache.get(n);try{r?.finalize()}catch{}this._stmtCache.delete(n)}}this._stmtCache.set(e,t)}return t}setSynchronous(e){this.db.run(`PRAGMA synchronous = ${e};`)}clearCache(){for(let e of this._stmtCache.values())try{e.finalize()}catch{}this._stmtCache.clear()}}function $t(e){if(e===":memory:")return[];return[e,`${e}-wal`,`${e}-shm`,`${e}-journal`].filter((t)=>Ct(t))}function ie(e){for(let t of $t(e))try{At(t)}catch{}}import{Compile as Ht}from"typebox/compile";class le{db;tableName;metricsHook;stmtCache=new Map;constructor(e){this.db=e.db,this.tableName=e.tableName,this.metricsHook=e.metricsHook}_getStmt(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.db.prepare(e);return this.stmtCache.set(e,n),n}exec(e,t,n="raw"){let r=performance.now(),s=this._getStmt(e).run(...t??[]);return this._emit(n,e,performance.now()-r,s.changes),s}all(e,t,n="read"){let r=performance.now(),s=this._getStmt(e).all(...t??[]);return this._emit(n,e,performance.now()-r,s.length),s}get(e,t,n="read"){let r=performance.now(),s=this._getStmt(e).get(...t??[]);return this._emit(n,e,performance.now()-r,s?1:0),s??null}*iterate(e,t,n="read"){let r=performance.now(),s=this._getStmt(e).iterate(...t??[]),a=0;for(let o of s)a++,yield o;this._emit(n,e,performance.now()-r,a)}_emit(e,t,n,r){if(!this.metricsHook)return;this.metricsHook({table:this.tableName,operation:e,sql:t,durationMs:n,rowCount:r})}}class G extends Error{code;trace;context;constructor(e,t){super(e);this.name="ORMError",this.code=t.code,this.trace=t.trace,this.context=t.context??{}}}var xe=[];function Ee(e,t){xe.push({label:e,time:Date.now(),details:t})}function Oe(){xe.pop()}function _e(){return xe.slice()}function C(e,t,n){Ee(e,t);try{return n()}finally{Oe()}}function O(e,t,n){throw new G(t,{code:e,trace:_e(),context:n})}import{IsObject as W,IsArray as ue,IsString as Je,IsNumber as Xe,IsInteger as Ye,IsBoolean as Ce,IsLiteral as ze,IsOptional as Mt}from"typebox";function Ne(e){if(Mt(e))return{schema:e,optional:!0};return{schema:e,optional:!1}}function Ae(e){let t=e;if(t.anyOf&&Array.isArray(t.anyOf))return t.anyOf;return null}function It(e){return e.const}function vt(e){let t=e;if(t.properties&&typeof t.properties==="object"&&t.properties!==null)return t.properties;return null}function $e(e){let t=Ae(e);if(t)return t.some((n)=>{return n.type==="null"});return!1}function Me(e){if(Ye(e))return"INTEGER";if(Xe(e))return"REAL";if(Ce(e))return"INTEGER";if(Je(e))return"TEXT";if(ze(e)){let t=It(e);if(typeof t==="number")return Number.isInteger(t)?"INTEGER":"REAL";if(typeof t==="boolean")return"INTEGER";return"TEXT"}if($e(e)){let t=Ae(e);if(t){let n=t.find((r)=>{return r.type!=="null"});if(n)return Me(n)}}return"TEXT"}function Ze(e){if(Je(e)||Xe(e)||Ye(e)||Ce(e)||ze(e))return!0;if($e(e)){let t=Ae(e);if(t){let n=t.find((r)=>{return r.type!=="null"});if(!n)return!1;return Ze(n)}}return!1}function Lt(e){if(!W(e))return!1;let t=vt(e);if(!t)return!1;for(let n of Object.values(t)){if(ue(n)||W(n))continue;let{schema:r}=Ne(n);if(ue(r)||W(r))continue;if(Ze(r))continue;return!1}return!0}function ke(e,t=[],n=0,r=!1){let s=[];for(let[a,o]of Object.entries(e)){if(ue(o)){let{optional:c}=Ne(o);if(r&&n===0&&W(o.items))continue;let d=t.length>0?[...t,a].join("__"):a;s.push({name:d,sqlType:"TEXT",nullable:c,optional:c,path:t.length>0?[...t,a]:void 0});continue}if(W(o)&&n<2&&Lt(o)){s.push(...ke(o.properties,[...t,a],n+1,r));continue}let{schema:i,optional:l}=Ne(o),u=l||$e(i),m=t.length>0?[...t,a].join("__"):a;s.push({name:m,sqlType:W(i)?"TEXT":Me(i),nullable:u,optional:u,path:t.length>0?[...t,a]:void 0,isBoolean:Ce(i)})}return s}function ne(e){if(!e)return;let t=[];for(let[n,r]of Object.entries(e))t.push({name:n,expr:r.expr,sqlType:Me(r.type)});return t}function J(e,t,n){let r=[];for(let[i,l]of Object.entries(t.properties))if(ue(l)&&W(l.items)){let u=l.items,m=`${e}__${i}`,c=ke(u.properties,[],0,!1),d=new Map,p=new Map;for(let h of c)if(d.set(h.name,h),h.path)p.set(h.path.join("."),h);r.push({fieldName:i,tableName:m,itemSchema:u,columns:c,columnByName:d,columnByPath:p})}let s=ke(t.properties,[],0,!0);if(n)for(let i of n)s.push({name:i.name,sqlType:i.sqlType??"TEXT",nullable:!0,optional:!0,generated:!0,generatedExpr:i.expr});let a=new Map,o=new Map;for(let i of s)if(o.set(i.name,i),i.path)a.set(i.path.join("."),i);return{tableName:e,columns:s,subTables:r,columnByPath:a,columnByName:o}}function Ie(e,t){let n=[],r=e.columns.map((s)=>{let a=!s.nullable?" NOT NULL":"",o=s.name===t?" PRIMARY KEY":"",i=s.generated&&s.generatedExpr?` GENERATED ALWAYS AS (${s.generatedExpr}) STORED`:"";return` "${s.name}" ${s.sqlType}${o}${a}${i}`});n.push(`CREATE TABLE IF NOT EXISTS "${e.tableName}" (
|
|
3
|
+
${r.join(`,
|
|
4
4
|
`)}
|
|
5
|
-
)`);for(let
|
|
6
|
-
${
|
|
5
|
+
)`);for(let s of e.subTables){let a=[' "_id" INTEGER PRIMARY KEY AUTOINCREMENT',` "_owner_id" ${e.columns.find((o)=>o.name===t)?.sqlType??"TEXT"} NOT NULL`,' "_index" INTEGER NOT NULL',...s.columns.map((o)=>{let i=!o.nullable?" NOT NULL":"";return` "${o.name}" ${o.sqlType}${i}`})];n.push(`CREATE TABLE IF NOT EXISTS "${s.tableName}" (
|
|
6
|
+
${a.join(`,
|
|
7
7
|
`)}
|
|
8
|
-
)`),X.push(`CREATE INDEX IF NOT EXISTS "idx_${Y.tableName}__owner" ON "${Y.tableName}" ("_owner_id")`)}return X}function PA(A,$,X,Z){let Y=Z??`idx_${A}__${$.join("_")}`,G=X?"UNIQUE ":"",H=$.map((Q)=>`"${Q}"`).join(", ");return`CREATE ${G}INDEX IF NOT EXISTS "${Y}" ON "${A}" (${H})`}function c(A,$){let X={};for(let Z of $.columns){let Y=A[Z.name];if(Y===void 0||Y===null)X[Z.name]=null;else if(Z.sqlType==="TEXT"&&typeof Y==="object")X[Z.name]=JSON.stringify(Y);else if(Z.sqlType==="INTEGER"&&typeof Y==="boolean")X[Z.name]=Y?1:0;else X[Z.name]=CA(Y)}return X}function i(A,$,X){return $.map((Z,Y)=>{let G={_owner_id:A,_index:Y};for(let H of X.columns){let Q=Z[H.name];if(Q===void 0||Q===null)G[H.name]=null;else if(H.sqlType==="TEXT"&&typeof Q==="object")G[H.name]=JSON.stringify(Q);else if(H.sqlType==="INTEGER"&&typeof Q==="boolean")G[H.name]=Q?1:0;else G[H.name]=CA(Q)}return G})}function CA(A){if(A===null||A===void 0)return null;if(typeof A==="string"||typeof A==="number"||typeof A==="boolean"||typeof A==="bigint")return A;if(typeof A==="object")return JSON.stringify(A);return String(A)}function jA(A,$,X){let Z={};for(let Y of $.columns){let G=A[Y.name];if(Y.sqlType==="TEXT"&&typeof G==="string")try{let H=JSON.parse(G);Z[Y.name]=typeof H==="object"?H:G}catch{Z[Y.name]=G}else if(Y.sqlType==="INTEGER"&&typeof G==="number")Z[Y.name]=G;else Z[Y.name]=G??null}for(let Y of $.subTables)Z[Y.fieldName]=X.get(Y.tableName)??[];return Z}function X$(A){return typeof A==="object"&&A!==null}function Z$(A,$){if("eq"in $)return{sql:`"${A}" = ?`,params:[$.eq]};if("ne"in $)return{sql:`"${A}" != ?`,params:[$.ne]};if("gt"in $)return{sql:`"${A}" > ?`,params:[$.gt]};if("gte"in $)return{sql:`"${A}" >= ?`,params:[$.gte]};if("lt"in $)return{sql:`"${A}" < ?`,params:[$.lt]};if("lte"in $)return{sql:`"${A}" <= ?`,params:[$.lte]};if("like"in $)return{sql:`"${A}" LIKE ?`,params:[$.like]};if("between"in $){let[X,Z]=$.between;return{sql:`"${A}" BETWEEN ? AND ?`,params:[X,Z]}}if("in"in $){let X=$.in,Z=X.map(()=>"?").join(", ");return{sql:`"${A}" IN (${Z})`,params:[...X]}}if("notIn"in $){let X=$.notIn,Z=X.map(()=>"?").join(", ");return{sql:`"${A}" NOT IN (${Z})`,params:[...X]}}if("isNull"in $)return{sql:`"${A}" IS NULL`,params:[]};if("isNotNull"in $)return{sql:`"${A}" IS NOT NULL`,params:[]};O("UNKNOWN_FILTER",`foxdb: unknown filter operator for column "${A}"`,{column:A})}function r(A){if(!A||Object.keys(A).length===0)return{sql:"",params:[]};let $=[],X=[];for(let[Z,Y]of Object.entries(A)){if(!X$(Y))continue;let G=Z$(Z,Y);$.push(G.sql),X.push(...G.params)}if($.length===0)return{sql:"",params:[]};return{sql:`WHERE ${$.join(" AND ")}`,params:X}}function Y$(A){if(!A)return"";let $=globalThis.Array.isArray(A)?A:[A];if($.length===0)return"";return`ORDER BY ${$.map((Z)=>`"${Z.column}" ${Z.direction??"ASC"}`).join(", ")}`}function H$(A,$){let X=[],Z=[];if(A!==void 0)X.push("LIMIT ?"),Z.push(A);if($!==void 0)X.push("OFFSET ?"),Z.push($);return{sql:X.join(" "),params:Z}}function t(A,$){let{sql:X,params:Z}=r($.where),Y=Y$($.orderBy),{sql:G,params:H}=H$($.limit,$.offset),Q=[`SELECT * FROM "${A}"`,X,Y,G].filter(Boolean).join(" "),_=[`SELECT COUNT(*) as "_count" FROM "${A}"`,X].filter(Boolean).join(" ");return{sql:Q,params:[...Z,...H],countSql:_,countParams:Z}}function u(A,$){let X=Object.keys($),Z=X.map((G)=>`"${G}"`).join(", "),Y=X.map(()=>"?").join(", ");return{sql:`INSERT INTO "${A}" (${Z}) VALUES (${Y})`,params:X.map((G)=>$[G])}}function DA(A,$,X,Z){let Y=Object.keys($),G=Y.map((K)=>`"${K}"`).join(", "),H=Y.map(()=>"?").join(", "),Q=X.map((K)=>`"${K}"`).join(", "),_=Z.map((K)=>`"${K}" = excluded."${K}"`).join(", ");return{sql:`INSERT INTO "${A}" (${G}) VALUES (${H}) ON CONFLICT (${Q}) DO UPDATE SET ${_}`,params:Y.map((K)=>$[K])}}function OA(A,$,X,Z){let Y=Object.entries(Z).filter(([H])=>H!==$);if(Y.length===0)O("NO_COLUMNS_TO_UPDATE","foxdb: no columns to update",{table:A});let G=Y.map(([H])=>`"${H}" = ?`).join(", ");return{sql:`UPDATE "${A}" SET ${G} WHERE "${$}" = ?`,params:[...Y.map(([,H])=>H),X]}}var JA={createdAt:"createdAt",updatedAt:"updatedAt"};function QA(A,$){if(A===!1||!A)return{createdAt:null,updatedAt:null};let X=typeof A==="object"&&A.createdAt!==void 0?A.createdAt:JA.createdAt,Z=typeof A==="object"&&A.updatedAt!==void 0?A.updatedAt:JA.updatedAt,Y=new Set($.columns.map((G)=>G.name));return{createdAt:Y.has(X)?null:X,updatedAt:Y.has(Z)?null:Z}}class a{tableName;meta;validator;db;descriptor;_entityProto=null;_timestampNames;_materialize;_materializeMany;_events;setEventBus(A){this._events=A}constructor(A,$,X){this.tableName=A,this.descriptor=$,this.db=X,this.meta=m(A,$.schema),this._timestampNames=QA($.timestamps,this.meta),this.validator=G$($.schema),this._migrate()}setMaterializer(A,$){this._materialize=A,this._materializeMany=$;let X=Object.create(null);Object.defineProperty(X,"materialize",{value:function(){return A(this)},writable:!1,enumerable:!1,configurable:!1}),this._entityProto=X}_wrap(A){if(!this._entityProto)return A;let $=Object.create(this._entityProto);return Object.assign($,A),$}_record(A){return A}_emit(A,$){if(!this._events)return;let X=Date.now(),Y={...{table:this.tableName,operation:A,timestamp:X},...$},G=`${this.tableName}.${A}`;if(this._events.has(G))this._events.emit(G,Y);let H;if(A.startsWith("find")||A==="count")H="read";else if(A==="delete"||A==="deleteWhere"||A==="flush")H="delete";else H="write";let Q=`${this.tableName}.${H}`;if(this._events.has(Q))this._events.emit(Q,{...Y,operation:H})}_migrate(){let A=this.descriptor.primaryKey.name,$=GA(this.meta,A);this.db.transaction(()=>{for(let X of $)this.db.exec(X);for(let X of this.descriptor.indexes??[])this.db.exec(PA(this.tableName,X.columns.map((Z)=>Z.name),X.unique??!1,X.name))}),this.db.clearCache()}parse(A){return this.validator.Parse(A)}check(A){return this.validator.Check(A)}insert(A){return x("repository.insert",{table:this.tableName},()=>{let $=this.parse(A),X=this._record($),Z=Date.now();if(this._timestampNames.createdAt)X[this._timestampNames.createdAt]=Z;if(this._timestampNames.updatedAt)X[this._timestampNames.updatedAt]=Z;return this.db.transaction(()=>{let Y=c(X,this.meta),{sql:G,params:H}=u(this.tableName,Y);this.db.prepare(G).run(...H);let Q=X[this.descriptor.primaryKey.name];for(let _ of this.meta.subTables){let K=X[_.fieldName];if(!globalThis.Array.isArray(K)||K.length===0)continue;let C=i(Q,K,_);for(let J of C){let{sql:E,params:T}=u(_.tableName,J);this.db.prepare(E).run(...T)}}}),this._emit("insert",{data:$}),this._wrap(this._record($))})}insertMany(A){return x("repository.insertMany",{table:this.tableName},()=>{let $=A.map((X)=>this.parse(X));return this.db.transaction(()=>{for(let X of $)this._insertParsed(this._record(X))}),this._emit("insertMany",{data:$}),$.map((X)=>this._wrap(this._record(X)))})}_insertParsed(A){let $=Date.now();if(this._timestampNames.createdAt)A[this._timestampNames.createdAt]=$;if(this._timestampNames.updatedAt)A[this._timestampNames.updatedAt]=$;let X=c(A,this.meta),{sql:Z,params:Y}=u(this.tableName,X);this.db.prepare(Z).run(...Y);let G=A[this.descriptor.primaryKey.name];for(let H of this.meta.subTables){let Q=A[H.fieldName];if(!globalThis.Array.isArray(Q)||Q.length===0)continue;let _=i(G,Q,H);for(let K of _){let{sql:C,params:J}=u(H.tableName,K);this.db.prepare(C).run(...J)}}}upsert(A){return x("repository.upsert",{table:this.tableName},()=>{let $=this.parse(A.data),X=this._record($),Z=Date.now();if(this._timestampNames.createdAt)X[this._timestampNames.createdAt]=Z;if(this._timestampNames.updatedAt)X[this._timestampNames.updatedAt]=Z;let Y=c(X,this.meta),G=globalThis.Array.isArray(A.conflictTarget)?A.conflictTarget:[A.conflictTarget],H=Object.keys(Y),Q=A.update??H.filter((_)=>!G.includes(_));return this.db.transaction(()=>{let{sql:_,params:K}=DA(this.tableName,Y,G,Q);this.db.prepare(_).run(...K);let C=X[this.descriptor.primaryKey.name];for(let J of this.meta.subTables){this.db.prepare(`DELETE FROM "${J.tableName}" WHERE "_owner_id" = ?`).run(C);let E=X[J.fieldName];if(!globalThis.Array.isArray(E)||E.length===0)continue;let T=i(C,E,J);for(let k of T){let{sql:v,params:d}=u(J.tableName,k);this.db.prepare(v).run(...d)}}}),this._emit("upsert",{data:$}),this._wrap(this._record($))})}findById(A){return x("repository.findById",{table:this.tableName},()=>{let $=this._findByIdRaw(A);return this._emit("findById",{id:A,result:$}),$})}_findByIdRaw(A){let $=this.descriptor.primaryKey.name,Z=this.db.prepare(`SELECT * FROM "${this.tableName}" WHERE "${$}" = ? LIMIT 1`).get(A);if(!Z)return null;return this._wrap(this._hydrateOne(Z))}findMany(A={}){return x("repository.findMany",{table:this.tableName},()=>{let{sql:$,params:X}=t(this.tableName,A),G=this.db.prepare($).all(...X).map((H)=>this._wrap(this._hydrateOne(H,A.include)));return this._emit("findMany",{options:A,result:G}),G})}findPage(A={}){return x("repository.findPage",{table:this.tableName},()=>{let{sql:$,params:X,countSql:Z,countParams:Y}=t(this.tableName,A),G=this.db.prepare($).all(...X).map((_)=>this._wrap(this._hydrateOne(_,A.include))),H=this.db.prepare(Z).get(...Y),Q={data:G,total:H._count,limit:A.limit??G.length,offset:A.offset??0};return this._emit("findPage",{options:A,result:Q}),Q})}findOne(A={}){return x("repository.findOne",{table:this.tableName},()=>{let{sql:$,params:X}=t(this.tableName,{...A,limit:1}),Y=this.db.prepare($).get(...X),G=Y?this._wrap(this._hydrateOne(Y,A.include)):null;return this._emit("findOne",{options:A,result:G}),G})}findManyMaterialized(A={}){let $=this.findMany(A);if(!this._materializeMany)return $;let X=this._materializeMany($);if(this._entityProto){for(let Z of X)if(Object.getPrototypeOf(Z)!==this._entityProto)Object.setPrototypeOf(Z,this._entityProto)}return X}count(A){return x("repository.count",{table:this.tableName},()=>{let{sql:$,params:X}=r(A),Z=`SELECT COUNT(*) as "_count" FROM "${this.tableName}" ${$}`.trim(),Y=this.db.prepare(Z).get(...X);return this._emit("count",{where:A,result:Y._count}),Y._count})}update(A){return x("repository.update",{table:this.tableName},()=>{let $=this._record(A),X=this.descriptor.primaryKey.name,Z=$[X];if(Z===void 0||Z===null)O("UPDATE_MISSING_PK",`foxdb: update() requires primary key "${X}"`,{table:this.tableName,column:X});let Y=this._findByIdRaw(Z);if(!Y)return null;let G=this.parse({...Y,...A}),H=this._record(G);if(this._timestampNames.updatedAt)H[this._timestampNames.updatedAt]=Date.now();let Q=c(H,this.meta),_=Object.fromEntries(Object.entries(Q).filter(([C])=>C!==X));this.db.transaction(()=>{let{sql:C,params:J}=OA(this.tableName,X,Z,_);this.db.prepare(C).run(...J);for(let E of this.meta.subTables){this.db.prepare(`DELETE FROM "${E.tableName}" WHERE "_owner_id" = ?`).run(Z);let T=H[E.fieldName];if(!globalThis.Array.isArray(T)||T.length===0)continue;let k=i(Z,T,E);for(let v of k){let{sql:d,params:l}=u(E.tableName,v);this.db.prepare(d).run(...l)}}});let K=this._wrap(this._record(G));return this._emit("update",{id:Z,data:{...A}}),K})}deleteById(A){return x("repository.deleteById",{table:this.tableName},()=>{let $=this.descriptor.primaryKey.name,X=this.db.transaction(()=>{for(let Y of this.meta.subTables)this.db.prepare(`DELETE FROM "${Y.tableName}" WHERE "_owner_id" = ?`).run(A);return this.db.prepare(`DELETE FROM "${this.tableName}" WHERE "${$}" = ?`).run(A).changes>0});return this._emit("delete",{id:A}),X})}deleteWhere(A){return x("repository.deleteWhere",{table:this.tableName},()=>{let{sql:$,params:X}=r(A),Z=this.descriptor.primaryKey.name,Y=this.db.transaction(()=>{for(let Q of this.meta.subTables){let _=`DELETE FROM "${Q.tableName}" WHERE "_owner_id" IN (SELECT "${Z}" FROM "${this.tableName}" ${$})`.trim();this.db.prepare(_).run(...X)}let G=`DELETE FROM "${this.tableName}" ${$}`.trim();return this.db.prepare(G).run(...X).changes});return this._emit("deleteWhere",{where:A,result:Y}),Y})}flush(){x("repository.flush",{table:this.tableName},()=>{this.db.exec(`DELETE FROM "${this.tableName}"`);for(let A of this.meta.subTables)this.db.exec(`DELETE FROM "${A.tableName}"`);this._emit("flush",{})})}drop(){for(let A of this.meta.subTables)this.db.exec(`DROP TABLE IF EXISTS "${A.tableName}"`);this.db.exec(`DROP TABLE IF EXISTS "${this.tableName}"`)}_hydrateOne(A,$){let X=new Map,Z=this.descriptor.primaryKey.name,Y=A[Z];for(let G of this.meta.subTables){if($&&!$.includes(G.fieldName)){X.set(G.tableName,[]);continue}let Q=this.db.prepare(`SELECT * FROM "${G.tableName}" WHERE "_owner_id" = ? ORDER BY "_index" ASC`).all(Y).map((_)=>{let{_id:K,_owner_id:C,_index:J,...E}=_;return E});X.set(G.tableName,Q)}return jA(A,this.meta,X)}raw(A,...$){return this.db.prepare(A).all(...$)}}class TA{tables;relations=[];constructor(A){this.tables=A}from(A){let $=A;return{scalar:(X)=>({to:(Z,Y,G)=>{let H={ownerTable:$,ownerField:X,targetTable:Z,targetField:Y,kind:"scalar",as:G?.as};return this.relations.push(H),H}}),subTable:(X,Z)=>({to:(Y,G,H)=>{let Q={ownerTable:$,ownerField:`${X}.${Z}`,targetTable:Y,targetField:G,kind:"subTable",as:H?.as};return this.relations.push(Q),Q}})}}build(){return this.relations}}function WA(A){return new TA(A)}import{Type as j}from"typebox";import n from"typebox/schema";var J$=j.Object({key:j.String(),value:j.String(),encoding:j.String(),updatedAt:j.Integer()}),qA=n.Compile(J$),Q$=j.String(),gA=j.Record(j.String(),j.Unknown()),W$=j.Array(j.String()),z$=j.Array(j.Object({ownerTable:j.String(),ownerField:j.String(),targetTable:j.String(),targetField:j.String(),kind:j.Union([j.Literal("scalar"),j.Literal("subTable")]),as:j.Optional(j.String())})),U$=j.String(),LX=n.Compile(Q$),IA=n.Compile(gA),RA=n.Compile(W$),xA=n.Compile(z$),MX=n.Compile(U$),F$="plain",NA="json",SA="deflate-base64";class N{db;static KEY_SCHEMA_HASH="schemaHash";static KEY_SCHEMA_JSON="schemaJSON";static KEY_TABLES="tables";static KEY_RELATIONS="relations";static KEY_VERSION="version";constructor(A){this.db=A,this.db.exec(`
|
|
8
|
+
)`),n.push(`CREATE INDEX IF NOT EXISTS "idx_${s.tableName}__owner" ON "${s.tableName}" ("_owner_id")`)}return n}function et(e,t,n,r,s,a){let o=r??`idx_${e}__${t.join("_")}`,i=n?"UNIQUE ":"",l=t.map((m)=>`"${m}"`).join(", "),u=s?` WHERE ${s}`:"";return`CREATE ${i}INDEX IF NOT EXISTS "${o}" ON "${e}" (${l})${u}`}function ee(e,t){if(e===void 0||e===null)return null;if(t==="TEXT"&&typeof e==="object")return JSON.stringify(e);if(t==="INTEGER"&&typeof e==="boolean")return e?1:0;return Bt(e)}function te(e,t){let n=e;for(let r of t){if(n===null||n===void 0)return;if(typeof n!=="object")return;n=n[r]}return n}function Z(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let a=t[s];if(!(a in r))r[a]={};r=r[a]}r[t[t.length-1]]=n}function U(e,t,n){let r={};if(!n?.size)for(let s of t.columns){if(s.generated)continue;let a=s.path?te(e,s.path):e[s.name];r[s.name]=ee(a,s.sqlType)}else for(let s of t.columns){if(s.generated)continue;let a=s.path?te(e,s.path):e[s.name],o=ee(a,s.sqlType),i=n.get(s.name);if(i)o=i.encode(o);r[s.name]=o}return r}function tt(e,t,n){let r={};for(let s of t.columns){if(s.generated)continue;if(!(s.name in e)&&!s.path)continue;let a;if(s.path)a=te(e,s.path);else a=e[s.name];if(a===void 0)continue;let o=ee(a,s.sqlType),i=n?.get(s.name);if(i)o=i.encode(o);r[s.name]=o}return r}function X(e,t,n,r){let s=Array(t.length);if(!r?.size)for(let a=0;a<t.length;a++){let o=t[a];if(o===null||typeof o!=="object")throw TypeError("Sub-table item must be an object");let i=o,l={_owner_id:e,_index:a};for(let u of n.columns){let m=u.path?te(i,u.path):i[u.name];l[u.name]=ee(m,u.sqlType)}s[a]=l}else for(let a=0;a<t.length;a++){let o=t[a];if(o===null||typeof o!=="object")throw TypeError("Sub-table item must be an object");let i=o,l={_owner_id:e,_index:a};for(let u of n.columns){let m=u.path?te(i,u.path):i[u.name],c=ee(m,u.sqlType),d=r.get(u.name);if(d)c=d.encode(c);l[u.name]=c}s[a]=l}return s}function Bt(e){if(e===null||e===void 0)return null;if(typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e;if(typeof e==="object")return JSON.stringify(e);return String(e)}function ce(e,t,n){if(t==="TEXT"&&typeof e==="string"){let r=e.charCodeAt(0);if(r===123||r===91)try{let s=JSON.parse(e);return typeof s==="object"?s:e}catch{return e}return e}if(t==="INTEGER"&&typeof e==="number")return n?e===1:e;return e??null}function Dt(e,t){let n={};for(let r of t.columns){let s=ce(e[r.name],r.sqlType,r.isBoolean);if(r.path)if(r.path.length===1)n[r.path[0]]=s;else Z(n,r.path,s);else n[r.name]=s}return n}function de(e,t,n,r,s,a){if(!r?.size&&!s&&!t.subTables.length)return Dt(e,t);let o={};if(!s)if(!r?.size)for(let i of t.columns){let l=ce(e[i.name],i.sqlType,i.isBoolean);if(i.path)if(i.path.length===1)o[i.path[0]]=l;else Z(o,i.path,l);else o[i.name]=l}else for(let i of t.columns){let l=e[i.name],u=r.get(i.name);if(u)l=u.decode(l);let m=ce(l,i.sqlType,i.isBoolean);if(i.path)if(i.path.length===1)o[i.path[0]]=m;else Z(o,i.path,m);else o[i.name]=m}else{let i=new Set;for(let l of s)if(i.add(l),!l.includes(".")){for(let u of t.columns)if(u.path&&u.path[0]===l)i.add(u.name)}else{let u=t.columnByPath.get(l);if(u)i.add(u.name)}for(let l of t.columns){if(!i.has(l.name))continue;let u=e[l.name],m=r?.get(l.name);if(m)u=m.decode(u);let c=ce(u,l.sqlType,l.isBoolean);if(l.path)if(l.path.length===1)o[l.path[0]]=c;else Z(o,l.path,c);else o[l.name]=c}for(let l of Object.keys(e)){if(i.has(l))continue;if(l.includes("__")){let u=l.split("__"),m=e[l];if(typeof m==="string"){let c=m.charCodeAt(0);if(c===123||c===91)try{let d=JSON.parse(m);if(typeof d==="object")m=d}catch{}}Z(o,u,m)}}}for(let i of t.subTables)if(a&&!a.includes(i.fieldName))o[i.fieldName]=[];else o[i.fieldName]=n.get(i.tableName)??[];return o}var nt={encode(e){if(typeof e!=="string")return e;let t=new TextEncoder().encode(e);return Bun.gzipSync(t.buffer)},decode(e){if(!(e instanceof Uint8Array))return e;return new TextDecoder().decode(Bun.gunzipSync(e.buffer))}};function Pt(e){return typeof e==="object"&&e!==null}function ve(e){return e.replace(/'/g,"''")}function Qt(e,t){let n=e.split(".");if(n.length<2)return null;if(t){let o=t.columnByPath.get(e);if(o)return{sql:`"${o.name}"`};for(let i=n.length-1;i>=1;i--){let l=n.slice(0,i).join("."),u=n.slice(i).join("."),m=t.columnByPath.get(l);if(m&&m.sqlType==="TEXT")return{sql:`JSON_EXTRACT("${m.name.replace(/"/g,'""')}", '$.${ve(u)}')`}}}let r=n[0],s=n.slice(1).join(".");return{sql:`JSON_EXTRACT("${r.replace(/"/g,'""')}", '$.${ve(s)}')`}}function B(e){if(e!==null&&typeof e==="object")return JSON.stringify(e);return e}function Le(e,t,n){let r=Qt(e,n),s=r?r.sql:`"${e}"`;if("eq"in t)return{sql:`${s} = ?`,params:[B(t.eq)]};if("ne"in t)return{sql:`${s} != ?`,params:[B(t.ne)]};if("gt"in t)return{sql:`${s} > ?`,params:[B(t.gt)]};if("gte"in t)return{sql:`${s} >= ?`,params:[B(t.gte)]};if("lt"in t)return{sql:`${s} < ?`,params:[B(t.lt)]};if("lte"in t)return{sql:`${s} <= ?`,params:[B(t.lte)]};if("like"in t)return{sql:`${s} LIKE ?`,params:[B(t.like)]};if("between"in t){let[a,o]=t.between;return{sql:`${s} BETWEEN ? AND ?`,params:[B(a),B(o)]}}if("in"in t){let a=t.in,o=a.map(()=>"?").join(", ");return{sql:`${s} IN (${o})`,params:a.map(B)}}if("notIn"in t){let a=t.notIn,o=a.map(()=>"?").join(", ");return{sql:`${s} NOT IN (${o})`,params:a.map(B)}}if("isNull"in t)return{sql:`${s} IS NULL`,params:[]};if("isNotNull"in t)return{sql:`${s} IS NOT NULL`,params:[]};if("arraySome"in t)return{sql:`EXISTS (SELECT 1 FROM json_each(${s}) WHERE value = ?)`,params:[B(t.arraySome)]};if("arrayNot"in t)return{sql:`NOT EXISTS (SELECT 1 FROM json_each(${s}) WHERE value = ?)`,params:[B(t.arrayNot)]};if("isEmpty"in t)if(t.isEmpty)return{sql:`(json_array_length(${s}) = 0 OR ${s} IS NULL)`,params:[]};else return{sql:`json_array_length(${s}) > 0`,params:[]};if("fastArrayIsEmpty"in t)if(t.fastArrayIsEmpty)return{sql:`(${s} = '[]' OR ${s} IS NULL)`,params:[]};else return{sql:`(${s} != '[]' AND ${s} IS NOT NULL)`,params:[]};if("fastArraySome"in t){let a=JSON.stringify([t.fastArraySome]),o=a.substring(1,a.length-1);return{sql:`(',' || REPLACE(REPLACE(${s}, '[', ''), ']', '') || ',') LIKE ?`,params:[`%,${o},%`]}}if("fastArrayNot"in t){let a=JSON.stringify([t.fastArrayNot]),o=a.substring(1,a.length-1);return{sql:`(',' || REPLACE(REPLACE(${s}, '[', ''), ']', '') || ',') NOT LIKE ?`,params:[`%,${o},%`]}}O("UNKNOWN_FILTER",`foxdb: unknown filter operator for column "${e}"`,{column:e})}function qt(e){if(typeof e!=="object"||e===null)return!1;let t=e;if("AND"in t&&Array.isArray(t.AND))return!0;if("OR"in t&&Array.isArray(t.OR))return!0;if("NOT"in t&&typeof t.NOT==="object"&&t.NOT!==null)return!0;return!1}function Y(e){if(!e||typeof e!=="object"||Object.keys(e).length===0)return!0;let t=e,n=Object.keys(t);if(n.length===1&&n[0]==="AND"&&Array.isArray(t.AND)&&t.AND.length===0)return!0;if(n.length===1&&n[0]==="OR"&&Array.isArray(t.OR)&&t.OR.some(Y))return!0;if(n.length===1&&n[0]==="NOT"&&re(t.NOT))return!0;return!1}function re(e){if(!e||typeof e!=="object")return!1;let t=e,n=Object.keys(t);if(n.length===1&&n[0]==="OR"&&Array.isArray(t.OR)&&t.OR.length===0)return!0;if(n.length===1&&n[0]==="AND"&&Array.isArray(t.AND)&&t.AND.some(re))return!0;if(n.length===1&&n[0]==="NOT"&&Y(t.NOT))return!0;return!1}function me(e,t,n){let r=[],s=[];if(t)r.push(`"${t}" IS NULL`);if(!e||Object.keys(e).length===0){if(r.length===0)return{sql:"",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}if(qt(e)){let o=e;if(o.AND)for(let i of o.AND){if(Y(i))continue;if(re(i)){if(r.push("1=0"),r.length===1)return{sql:"WHERE 1=0",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}let l=me(i,void 0,n);if(l.sql)r.push(`(${l.sql.replace(/^WHERE\s+/,"")})`),s.push(...l.params)}if(o.OR){let i=[],l=[];for(let u of o.OR){if(Y(u)){i.length=0;break}if(re(u))continue;let m=me(u,void 0,n);if(m.sql)i.push(m.sql.replace(/^WHERE\s+/,"")),l.push(...m.params)}if(i.length>0)r.push(`(${i.join(" OR ")})`),s.push(...l);else if(!o.OR.some(Y))r.push("1=0")}if(o.NOT){if(Y(o.NOT))r.push("1=0");else if(!re(o.NOT)){let i=me(o.NOT,void 0,n);if(i.sql)r.push(`NOT (${i.sql.replace(/^WHERE\s+/,"")})`),s.push(...i.params)}}}let a=e._raw;if(a&&typeof a==="object"&&"sql"in a){let o=a;r.push(`(${o.sql})`),s.push(...o.params??[])}for(let[o,i]of Object.entries(e)){if(o==="AND"||o==="OR"||o==="NOT"||o==="_raw")continue;if(!Pt(i))continue;let l=Le(o,i,n);r.push(l.sql),s.push(...l.params)}if(r.length===0)return{sql:"",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}function P(e,t,n){return me(e,t,n)}function Q(e,t){if(!t)return`"${e}"`;let n=t.columnByPath.get(e);if(n)return`"${n.name}"`;let r=e.split(".");for(let s=r.length-1;s>=1;s--){let a=r.slice(0,s).join("."),o=r.slice(s).join("."),i=t.columnByPath.get(a);if(i&&i.sqlType==="TEXT")return`JSON_EXTRACT("${i.name.replace(/"/g,'""')}", '$.${ve(o)}')`}return`"${e}"`}function jt(e,t){if(!e)return"";let n=globalThis.Array.isArray(e)?e:[e];if(n.length===0)return"";return`ORDER BY ${n.map((s)=>{return`${Q(s.column,t)} ${s.direction??"ASC"}`}).join(", ")}`}function Ft(e,t){let n=[],r=[];if(e!==void 0)n.push("LIMIT ?"),r.push(e);if(t!==void 0)n.push("OFFSET ?"),r.push(t);return{sql:n.join(" "),params:r}}function Kt(e,t){let n=t.columnByName.get(e)||t.columnByPath.get(e);if(n)return[`"${n.name}"`];let r=[];for(let a of t.columns)if(a.path&&a.path[0]===e)r.push(`"${a.name}"`);if(r.length>0)return r;let s=e.split(".");for(let a=s.length-1;a>=1;a--){let o=s.slice(0,a).join("."),i=s.slice(a).join("."),l=t.columnByPath.get(o);if(l&&l.sqlType==="TEXT"){let u=s.join("__");return[`JSON_EXTRACT("${l.name}", '$.${i.replace(/'/g,"''")}') as "${u}"`]}}return[`"${e}"`]}function Be(e,t,n,r){let{sql:s,params:a}=P(t.where,t.includeDeleted?void 0:n,r),o=jt(t.orderBy,r),{sql:i,params:l}=Ft(t.limit,t.offset),u=t.select&&r?t.select.flatMap((p)=>Kt(p,r)).join(", "):"*";if(t.distinctOn&&t.distinctOn.length>0){let p=t.distinctOn.map((k)=>Q(k,r)).join(", "),h=[`SELECT ${u} FROM "${e}"`,s,`GROUP BY ${p}`,o,i].filter(Boolean).join(" "),T=[`SELECT COUNT(*) as "_count" FROM (SELECT 1 FROM "${e}"`,s,`GROUP BY ${p})`].filter(Boolean).join(" ");return{sql:h,params:[...a,...l],countSql:T,countParams:a}}let c=[`SELECT ${t.distinct?"DISTINCT ":""}${u} FROM "${e}"`,s,o,i].filter(Boolean).join(" "),d;if(t.distinct)d=[`SELECT COUNT(*) as "_count" FROM (SELECT DISTINCT ${u} FROM "${e}"`,s,")"];else d=[`SELECT COUNT(*) as "_count" FROM "${e}"`,s];return{sql:c,params:[...a,...l],countSql:d.filter(Boolean).join(" "),countParams:a}}function se(e,t,n,r){return Be(e,t,n,r)}function H(e,t){let n=Object.keys(t),r=n.map((a)=>`"${a}"`).join(", "),s=n.map(()=>"?").join(", ");return{sql:`INSERT INTO "${e}" (${r}) VALUES (${s})`,params:n.map((a)=>t[a])}}function pe(e,t,n=999){if(t.length===0)return[];let r=t[0],s=Object.keys(r),a=s.length,o=Math.floor(n/a);if(o<=0)O("TOO_MANY_COLUMNS",`foxdb: table "${e}" has too many columns for multi-value insert`);let i=[];for(let l=0;l<t.length;l+=o){let u=t.slice(l,l+o),m=s.map((p)=>`"${p}"`).join(", "),c=u.map(()=>{return`(${s.map(()=>"?").join(", ")})`}).join(", "),d=u.flatMap((p)=>s.map((h)=>p[h]));i.push({sql:`INSERT INTO "${e}" (${m}) VALUES ${c}`,params:d})}return i}function rt(e,t,n,r){let s=Object.keys(t),a=s.map((u)=>`"${u}"`).join(", "),o=s.map(()=>"?").join(", "),i=n.map((u)=>`"${u}"`).join(", "),l=r.map((u)=>`"${u}" = excluded."${u}"`).join(", ");return{sql:`INSERT INTO "${e}" (${a}) VALUES (${o}) ON CONFLICT (${i}) DO UPDATE SET ${l}`,params:s.map((u)=>t[u])}}function st(e,t,n,r,s=999){if(t.length===0)return[];let a=t[0],o=Object.keys(a),i=o.length,l=Math.floor(s/i);if(l<=0)O("TOO_MANY_COLUMNS",`foxdb: table "${e}" has too many columns for multi-value upsert`);let u=n.map((d)=>`"${d}"`).join(", "),m=r.map((d)=>`"${d}" = excluded."${d}"`).join(", "),c=[];for(let d=0;d<t.length;d+=l){let p=t.slice(d,d+l),h=o.map((D)=>`"${D}"`).join(", "),T=p.map(()=>{return`(${o.map(()=>"?").join(", ")})`}).join(", "),k=p.flatMap((D)=>o.map((oe)=>D[oe]));c.push({sql:`INSERT INTO "${e}" (${h}) VALUES ${T} ON CONFLICT (${u}) DO UPDATE SET ${m}`,params:k})}return c}function ot(e,t,n,r){let s=Object.entries(r).filter(([o])=>o!==t);if(s.length===0)O("NO_COLUMNS_TO_UPDATE","foxdb: no columns to update",{table:e});let a=s.map(([o])=>`"${o}" = ?`).join(", ");return{sql:`UPDATE "${e}" SET ${a} WHERE "${t}" = ?`,params:[...s.map(([,o])=>o),n]}}function at(e,t,n,r,s){let a=Object.entries(t);if(a.length===0)O("NO_COLUMNS_TO_UPDATE","foxdb: no columns to update",{table:e});let o=a.map(([u])=>`"${u}" = ?`).join(", "),{sql:i,params:l}=P(n,r,s);return{sql:`UPDATE "${e}" SET ${o} ${i}`.trim(),params:[...a.map(([,u])=>u),...l]}}function Wt(e){return e.replace(/'/g,"''")}function V(e,t){if(!t)return`"${e}"`;let n=t.columnByPath.get(e);if(n)return`"${n.name}"`;let r=e.split(".");for(let s=r.length-1;s>=1;s--){let a=r.slice(0,s).join("."),o=r.slice(s).join("."),i=t.columnByPath.get(a);if(i&&i.sqlType==="TEXT")return`JSON_EXTRACT("${i.name.replace(/"/g,'""')}", '$.${Wt(o)}')`}return`"${e}"`}function it(e,t,n,r){let{sql:s,params:a}=P(t.where,t.includeDeleted?void 0:n,r),o=[];if(t.groupBy)for(let d of t.groupBy){let p=V(d,r);o.push(`${p} as "${d.replace(/"/g,'""')}"`)}for(let[d,p]of Object.entries(t.aggregations))if("sum"in p&&p.sum)o.push(`SUM(${V(p.sum,r)}) as "${d}"`);else if("count"in p&&p.count)o.push(`COUNT(${p.count==="*"?"*":V(p.count,r)}) as "${d}"`);else if("avg"in p&&p.avg)o.push(`AVG(${V(p.avg,r)}) as "${d}"`);else if("min"in p&&p.min)o.push(`MIN(${V(p.min,r)}) as "${d}"`);else if("max"in p&&p.max)o.push(`MAX(${V(p.max,r)}) as "${d}"`);let i=t.groupBy?`GROUP BY ${t.groupBy.map((d)=>V(d,r)).join(", ")}`:"",l=[],u=[];if(t.having){for(let[d,p]of Object.entries(t.having))if(p&&typeof p==="object"&&!Array.isArray(p)){let h=Le(d,p,r);l.push(h.sql),u.push(...h.params)}}let m=l.length>0?`HAVING ${l.join(" AND ")}`:"";return{sql:`SELECT ${o.join(", ")} FROM "${e}" ${s} ${i} ${m}`.trim(),params:[...a,...u]}}function Ut(e,t,n,r){if("rowNumber"in t)return`ROW_NUMBER() OVER (${n}) as "${e}"`;if("rank"in t)return`RANK() OVER (${n}) as "${e}"`;if("denseRank"in t)return`DENSE_RANK() OVER (${n}) as "${e}"`;if("lead"in t){let s=Q(t.lead,r),a=t.offset??1;return`LEAD(${s}, ${a}) OVER (${n}) as "${e}"`}if("lag"in t){let s=Q(t.lag,r),a=t.offset??1;return`LAG(${s}, ${a}) OVER (${n}) as "${e}"`}return`"${e}"`}function lt(e,t,n,r){let{sql:s,params:a}=P(t.where,n,r),o=t.partitionBy&&t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map((h)=>Q(h,r)).join(", ")}`:"",i=t.orderBy?(Array.isArray(t.orderBy)?t.orderBy:[t.orderBy]).map((h)=>{return`${Q(h.column,r)} ${h.direction??"ASC"}`}):[],l=i.length>0?`ORDER BY ${i.join(", ")}`:"",u=[o,l].filter(Boolean).join(" "),m=u?u:"ORDER BY (SELECT NULL)",c=[];for(let[h,T]of Object.entries(t.select))c.push(Ut(h,T,m,r));let d=t.limit!==void 0?`LIMIT ${t.limit}`:"";return{sql:[`SELECT ${c.join(", ")} FROM "${e}"`,s,d].filter(Boolean).join(" "),params:a}}class fe{buffer=[];maxBuffer;tableName;db;prepare;onFlush;timer;constructor(e,t,n={},r){if(this.tableName=e,this.db=t,this.maxBuffer=n.maxBuffer??1000,this.prepare=r.prepare,this.onFlush=r.onFlush,n.flushIntervalMs)this.timer=setInterval(()=>this.flush(),n.flushIntervalMs)}insert(e){let t=this.prepare(e);if(this.buffer.push(t),this.buffer.length>=this.maxBuffer)this.flush()}flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0,this.buffer.length);this.db.transaction(()=>{let t=pe(this.tableName,e);for(let{sql:n,params:r}of t)this.db.prepare(n).run(...r)}),this.onFlush?.(e)}close(){if(this.timer)clearInterval(this.timer);this.flush()}}var De={createdAt:"createdAt",updatedAt:"updatedAt"};function Pe(e,t){if(e===!1||!e)return{createdAt:null,updatedAt:null};let n=typeof e==="object"&&e.createdAt!==void 0?e.createdAt:De.createdAt,r=typeof e==="object"&&e.updatedAt!==void 0?e.updatedAt:De.updatedAt,s=new Set(t.columns.map((a)=>a.name));return{createdAt:s.has(n)?n:null,updatedAt:s.has(r)?r:null}}class he{tableName;meta;validator;db;descriptor;_entityProto=null;_timestampNames;_materialize;_materializeMany;_events;_executor;_codecs;setEventBus(e){this._events=e}setMetricsHook(e){this._executor=new le({db:this.db,tableName:this.tableName,metricsHook:e})}constructor(e,t,n){this.tableName=e,this.descriptor=t,this.db=n,this._executor=new le({db:n,tableName:this.tableName}),this.meta=J(e,t.schema,ne(t.generated)),this._timestampNames=Pe(t.timestamps,this.meta),this.validator=Ht(t.schema);let r=new Map;if(t.compression?.algorithm==="gzip")for(let s of t.compression.columns)r.set(s.name,nt);this._codecs=r;for(let s of this.meta.columns)if(this._codecs.has(s.name))s.sqlType="BLOB";if(this._migrate(),t.eviction){if(n.scheduler.schedule(`evict:${e}`,30000,()=>this._runEviction()),t.eviction.maxRows&&!t.eviction.lruColumn)console.warn(`[foxdb] table "${e}" has eviction.maxRows without lruColumn. Eviction will use PK order, which is not true LRU.`)}}_ensureSelectPk(e){let t=this.descriptor.primaryKey.name;if(e.select&&e.include&&!e.select.includes(t))return{...e,select:[...e.select,t]};return e}_fetchRows(e,t){let n=this.descriptor.primaryKey.name,r=this.descriptor.softDelete?.column;if(!(!e.select&&e.where&&Object.keys(e.where).length>0)){let{sql:h,params:T}=se(this.tableName,e,r,this.meta);return this._executor.all(h,T,t)}let a={...e,select:[n],include:void 0},{sql:o,params:i}=se(this.tableName,a,r,this.meta),u=this._executor.all(o,i,t).map((h)=>h[n]).filter((h)=>typeof h==="string"||typeof h==="number");if(u.length===0)return[];if(u.length>500){let{sql:h,params:T}=se(this.tableName,e,r,this.meta);return this._executor.all(h,T,t)}let m=u.map(()=>"?").join(", "),c=`SELECT * FROM "${this.tableName}" WHERE "${n}" IN (${m})`,d=this._executor.all(c,u,t),p=new Map(u.map((h,T)=>[h,T]));return d.sort((h,T)=>{let k=h[n],D=T[n],oe=p.get(k)??0,ae=p.get(D)??0;return oe-ae}),d}setMaterializer(e,t){this._materialize=e,this._materializeMany=t;let n=Object.create(null);Object.defineProperty(n,"materialize",{value:function(){return e(this)},writable:!1,enumerable:!1,configurable:!1}),this._entityProto=n}_wrap(e){if(!this._entityProto)return e;let t=Object.create(this._entityProto);return Object.assign(t,e),t}_record(e){return Object.fromEntries(Object.entries(e))}_assertPk(e){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e;O("INSERT_INVALID_PK",`Primary key must be a scalar, got ${typeof e}`,{table:this.tableName})}_emit(e,t){if(!this._events)return;let n=Date.now(),s={...{table:this.tableName,operation:e,timestamp:n},...t},a=`${this.tableName}.${e}`;if(this._events.has(a))this._events.emit(a,s);let o;if(e.startsWith("find")||e==="count")o="read";else if(e==="delete"||e==="deleteWhere"||e==="flush")o="delete";else o="write";let i=`${this.tableName}.${o}`;if(this._events.has(i))this._events.emit(i,{...s,operation:o})}_migrate(){let e=this.descriptor.primaryKey.name,t=Ie(this.meta,e);this.db.transaction(()=>{for(let n of t)this.db.exec(n);for(let n of this.descriptor.indexes??[])this.db.exec(et(this.tableName,n.columns.map((r)=>r.name),n.unique??!1,n.name,n.where,n.include?.map((r)=>r.name)))}),this.db.clearCache()}_runEviction(){let e=this.descriptor.eviction;if(!e)return;let t=Date.now();if(e.ttlColumn&&e.ttlMs){let n=t-e.ttlMs;this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${e.ttlColumn}" < ?`,[n],"evict")}if(e.maxRows){let n=e.lruColumn??this.descriptor.primaryKey.name,s=this.db.prepare(`SELECT COUNT(*) as c FROM "${this.tableName}"`).get().c;if(s<=e.maxRows)return;let a=s-e.maxRows;this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${this.descriptor.primaryKey.name}" IN (
|
|
9
|
+
SELECT "${this.descriptor.primaryKey.name}" FROM "${this.tableName}"
|
|
10
|
+
ORDER BY "${n}" ASC
|
|
11
|
+
LIMIT ?
|
|
12
|
+
)`,[a],"evict")}}parse(e){return this.validator.Parse(e)}check(e){return this.validator.Check(e)}insert(e){return C("repository.insert",{table:this.tableName},()=>{let t=this.parse(e),n=this._record(t),r=Date.now();if(this._timestampNames.createdAt)n[this._timestampNames.createdAt]=r;if(this._timestampNames.updatedAt)n[this._timestampNames.updatedAt]=r;if(this.db.transaction(()=>{let s=U(n,this.meta,this._codecs),{sql:a,params:o}=H(this.tableName,s);this._executor.exec(a,o,"insert");let i=n[this.descriptor.primaryKey.name];for(let l of this.meta.subTables){let u=n[l.fieldName];if(!globalThis.Array.isArray(u)||u.length===0)continue;let m=X(this._assertPk(i),u,l,this._codecs);for(let c of m){let{sql:d,params:p}=H(l.tableName,c);this._executor.exec(d,p,"insert")}}}),this.descriptor.eviction)this._runEviction();return this._emit("insert",{data:n}),this._wrap(n)})}insertMany(e){return C("repository.insertMany",{table:this.tableName},()=>{let n=e.map((s)=>this.parse(s)).map((s)=>{let a=this._record(s),o=Date.now();if(this._timestampNames.createdAt)a[this._timestampNames.createdAt]=o;if(this._timestampNames.updatedAt)a[this._timestampNames.updatedAt]=o;return a}),r=n.map((s)=>U(s,this.meta,this._codecs));if(this.db.transaction(()=>{let s=pe(this.tableName,r);for(let{sql:a,params:o}of s)this._executor.exec(a,o,"insertMany");for(let a of n){let o=a[this.descriptor.primaryKey.name];for(let i of this.meta.subTables){let l=a[i.fieldName];if(!globalThis.Array.isArray(l)||l.length===0)continue;let u=X(this._assertPk(o),l,i,this._codecs);for(let m of u){let{sql:c,params:d}=H(i.tableName,m);this._executor.exec(c,d,"insertMany")}}}}),this.descriptor.eviction)this._runEviction();return this._emit("insertMany",{data:n}),n.map((s)=>this._wrap(s))})}createBatchWriter(e){let t=this;return new fe(this.tableName,this.db,e,{prepare(n){let r=t.parse(n),s=t._record(r),a=Date.now();if(t._timestampNames.createdAt)s[t._timestampNames.createdAt]=a;if(t._timestampNames.updatedAt)s[t._timestampNames.updatedAt]=a;return U(s,t.meta,t._codecs)},onFlush(n){if(t._emit("insertMany",{data:n}),t.descriptor.eviction&&Math.random()<0.2)t._runEviction()}})}upsert(e){return C("repository.upsert",{table:this.tableName},()=>{let t=this.parse(e.data),n=this._record(t),r=Date.now();if(this._timestampNames.createdAt)n[this._timestampNames.createdAt]=r;if(this._timestampNames.updatedAt)n[this._timestampNames.updatedAt]=r;let s=U(n,this.meta,this._codecs),a=globalThis.Array.isArray(e.conflictTarget)?e.conflictTarget:[e.conflictTarget],o=Object.keys(s),i=e.update??o.filter((l)=>!a.includes(l));if(this.descriptor.softDelete&&!i.includes(this.descriptor.softDelete.column))i.push(this.descriptor.softDelete.column),s[this.descriptor.softDelete.column]=null;if(this.db.transaction(()=>{let{sql:l,params:u}=rt(this.tableName,s,a,i);this._executor.exec(l,u,"upsert");let m=n[this.descriptor.primaryKey.name];for(let c of this.meta.subTables){this._executor.exec(`DELETE FROM "${c.tableName}" WHERE "_owner_id" = ?`,[m],"delete");let d=n[c.fieldName];if(!globalThis.Array.isArray(d)||d.length===0)continue;let p=X(this._assertPk(m),d,c,this._codecs);for(let h of p){let{sql:T,params:k}=H(c.tableName,h);this._executor.exec(T,k,"insert")}}}),this.descriptor.eviction)this._runEviction();return this._emit("upsert",{data:t}),this._wrap(this._record(t))})}upsertMany(e){return C("repository.upsertMany",{table:this.tableName},()=>{let n=e.data.map((l)=>this.parse(l)).map((l)=>{let u=this._record(l),m=Date.now();if(this._timestampNames.createdAt)u[this._timestampNames.createdAt]=m;if(this._timestampNames.updatedAt)u[this._timestampNames.updatedAt]=m;return u}),r=n.map((l)=>U(l,this.meta,this._codecs)),s=globalThis.Array.isArray(e.conflictTarget)?e.conflictTarget:[e.conflictTarget],a=Object.keys(r[0]??{}),o=e.update??a.filter((l)=>!s.includes(l));if(this.descriptor.softDelete&&!o.includes(this.descriptor.softDelete.column)){o.push(this.descriptor.softDelete.column);for(let l of r)l[this.descriptor.softDelete.column]=null}let i=0;if(this.db.transaction(()=>{let l=st(this.tableName,r,s,o);for(let{sql:u,params:m}of l){let c=this._executor.exec(u,m,"upsertMany");i+=c.changes}for(let u of n){let m=u[this.descriptor.primaryKey.name];for(let c of this.meta.subTables){this._executor.exec(`DELETE FROM "${c.tableName}" WHERE "_owner_id" = ?`,[m],"delete");let d=u[c.fieldName];if(!globalThis.Array.isArray(d)||d.length===0)continue;let p=X(this._assertPk(m),d,c,this._codecs);for(let h of p){let{sql:T,params:k}=H(c.tableName,h);this._executor.exec(T,k,"insert")}}}}),this.descriptor.eviction)this._runEviction();return this._emit("upsertMany",{data:n,result:i}),i})}findById(e){return C("repository.findById",{table:this.tableName},()=>{let t=this._findByIdRaw(e);return this._emit("findById",{id:e,result:t}),t})}_findByIdRaw(e){let t=this.descriptor.primaryKey.name,n=this.descriptor.softDelete?`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? AND "${this.descriptor.softDelete.column}" IS NULL LIMIT 1`:`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? LIMIT 1`,r=this._executor.get(n,[e],"findById");if(!r)return null;if(this.descriptor.eviction?.lruColumn&&Math.random()<0.1){let s=this.descriptor.eviction.lruColumn,a=this.descriptor.primaryKey.name;Promise.resolve().then(()=>{try{this._executor.exec(`UPDATE "${this.tableName}" SET "${s}" = ? WHERE "${a}" = ?`,[Date.now(),e])}catch{}})}return this._wrap(this._hydrateOne(r))}findMany(e={}){return C("repository.findMany",{table:this.tableName},()=>{let t=e.select&&e.include?this._ensureSelectPk({...e,select:e.select}):e,n=this._fetchRows(t,"findMany");if(this.descriptor.eviction?.lruColumn){let i=this.descriptor.eviction.lruColumn,l=this.descriptor.primaryKey.name,u=[];for(let m of n)if(Math.random()<0.1){let c=m[l];if(typeof c==="string"||typeof c==="number")u.push(c)}if(u.length>0){let m=Date.now(),c=u.map(()=>"?").join(", ");Promise.resolve().then(()=>{try{this._executor.exec(`UPDATE "${this.tableName}" SET "${i}" = ? WHERE "${l}" IN (${c})`,[m,...u])}catch{}})}}let r=this.descriptor.primaryKey.name,s=n.map((i)=>i[r]).filter((i)=>typeof i==="string"||typeof i==="number"),a=new Map;for(let i of this.meta.subTables){if(!(!e.include||e.include.some((d)=>d===i.fieldName)))continue;if(s.length===0)continue;let u=s.map(()=>"?").join(", "),m=this._executor.all(`SELECT * FROM "${i.tableName}" WHERE "_owner_id" IN (${u}) ORDER BY "_index" ASC`,s,"findMany"),c=new Map;for(let d of m){let p=d._owner_id;if(typeof p!=="string"&&typeof p!=="number")continue;if(!c.has(p))c.set(p,[]);c.get(p).push(d)}a.set(i.tableName,c)}let o=n.map((i)=>{let l=new Map;for(let u of this.meta.subTables){if(!(!e.include||e.include.some((h)=>h===u.fieldName)))continue;let c=a.get(u.tableName),d=i[r],p=typeof d==="string"||typeof d==="number"?d:void 0;l.set(u.tableName,p!==void 0?c?.get(p)??[]:[])}return this._wrap(this._hydrateOne(i,e.include,e.select,l))});return this._emit("findMany",{options:e,result:o}),o})}findPage(e={}){return C("repository.findPage",{table:this.tableName},()=>{let t=e.select&&e.include?this._ensureSelectPk(e):e,{countSql:n,countParams:r}=se(this.tableName,t,this.descriptor.softDelete?.column,this.meta),s=this._fetchRows(t,"findPage").map((i)=>this._wrap(this._hydrateOne(i,e.include,e.select))),a=this._executor.get(n,r,"count"),o={data:s,total:(a??{_count:0})._count,limit:e.limit??s.length,offset:e.offset??0};return this._emit("findPage",{options:e,result:o}),o})}findCursorPage(e){return C("repository.findCursorPage",{table:this.tableName},()=>{let t=e.orderBy.direction??"ASC",n=Q(e.orderBy.column,this.meta),r=e.limit??25,{sql:s,params:a}=P(e.where,this.descriptor.softDelete?.column,this.meta),o=`SELECT * FROM "${this.tableName}"`,i=[...a];if(e.cursor){let h=Q(e.cursor.column,this.meta),T=e.cursor.direction==="next"?t==="ASC"?">":"<":t==="ASC"?"<":">",k=`${h} ${T} ?`;if(i.push(e.cursor.value),s)o+=` ${s} AND ${k}`;else o+=` WHERE ${k}`}else if(s)o+=` ${s}`;let l=e.cursor?.direction==="prev"?t==="ASC"?"DESC":"ASC":t;o+=` ORDER BY ${n} ${l} LIMIT ${r}`;let m=this._executor.all(o,i,"findCursorPage").map((h)=>this._wrap(this._hydrateOne(h)));if(e.cursor?.direction==="prev")m.reverse();let c=m.length===r?{column:e.orderBy.column,value:m[m.length-1][e.orderBy.column]}:null,d=m.length>0?{column:e.orderBy.column,value:m[0][e.orderBy.column]}:null,p={data:m,nextCursor:c,prevCursor:d};return this._emit("findCursorPage",{options:e,result:p}),p})}findOne(e={}){return C("repository.findOne",{table:this.tableName},()=>{let t=e.select&&e.include?this._ensureSelectPk(e):e,n=this._fetchRows({...t,limit:1},"findOne"),r=n.length>0?n[0]:null,s=r?this._wrap(this._hydrateOne(r,e.include,e.select)):null;return this._emit("findOne",{options:e,result:s}),s})}*iterate(e={}){Ee("repository.iterate",{table:this.tableName});try{let t=e.select&&e.include?this._ensureSelectPk(e):e.select?this._ensureSelectPk(e):e,{sql:n,params:r}=Be(this.tableName,t,this.descriptor.softDelete?.column,this.meta),s=this._executor.iterate(n,r,"iterate");if(!e.include||e.include.length===0){for(let l of s)yield this._wrap(this._hydrateOne(l,void 0,e.select));return}let a=this.descriptor.primaryKey.name,o=100,i=[];for(let l of s)if(i.push(l),i.length>=o)yield*this._hydrateWindow(i,e.include,e.select),i=[];if(i.length>0)yield*this._hydrateWindow(i,e.include,e.select)}finally{Oe()}}*_hydrateWindow(e,t,n){let r=this.descriptor.primaryKey.name,s=e.map((o)=>o[r]).filter((o)=>typeof o==="string"||typeof o==="number"),a=new Map;for(let o of this.meta.subTables){if(!t.some((c)=>c===o.fieldName))continue;if(s.length===0)continue;let l=s.map(()=>"?").join(", "),u=this._executor.all(`SELECT * FROM "${o.tableName}" WHERE "_owner_id" IN (${l}) ORDER BY "_index" ASC`,s,"iterate"),m=new Map;for(let c of u){let d=c._owner_id;if(typeof d!=="string"&&typeof d!=="number")continue;if(!m.has(d))m.set(d,[]);m.get(d).push(c)}a.set(o.tableName,m)}for(let o of e){let i=new Map;for(let l of this.meta.subTables){if(!t.some((p)=>p===l.fieldName))continue;let m=a.get(l.tableName),c=o[r],d=typeof c==="string"||typeof c==="number"?c:void 0;i.set(l.tableName,d!==void 0?m?.get(d)??[]:[])}yield this._wrap(this._hydrateOne(o,t,n,i))}}findManyMaterialized(e={}){let t=this.findMany(e);if(!this._materializeMany)return t;let n=this._materializeMany(t);if(this._entityProto){for(let r of n)if(Object.getPrototypeOf(r)!==this._entityProto)Object.setPrototypeOf(r,this._entityProto)}return n}count(e){return C("repository.count",{table:this.tableName},()=>{let{sql:t,params:n}=P(e,this.descriptor.softDelete?.column,this.meta),r=`SELECT COUNT(*) as "_count" FROM "${this.tableName}" ${t}`.trim(),a=(this._executor.get(r,n,"count")??{_count:0})._count;return this._emit("count",{where:e,result:a}),a})}aggregate(e){return C("repository.aggregate",{table:this.tableName},()=>{let{sql:t,params:n}=it(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=this._executor.all(t,n,"aggregate");return this._emit("aggregate",{options:e,result:r}),r})}windowQuery(e){return C("repository.windowQuery",{table:this.tableName},()=>{let{sql:t,params:n}=lt(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=this._executor.all(t,n,"windowQuery");return this._emit("windowQuery",{options:e,result:r}),r})}update(e){return C("repository.update",{table:this.tableName},()=>{let t=this._record(e),n=this.descriptor.primaryKey.name,r=t[n];if(r===void 0||r===null)O("UPDATE_MISSING_PK",`foxdb: update() requires primary key "${n}"`,{table:this.tableName,column:n});let s=this._findByIdRaw(this._assertPk(r));if(!s)return null;let a=this.parse({...s,...e}),o=this._record(a);if(this._timestampNames.updatedAt)o[this._timestampNames.updatedAt]=Date.now();let i=U(o,this.meta,this._codecs),l=Object.fromEntries(Object.entries(i).filter(([m])=>m!==n));this.db.transaction(()=>{let{sql:m,params:c}=ot(this.tableName,n,this._assertPk(r),l);this._executor.exec(m,c,"update");for(let d of this.meta.subTables){this._executor.exec(`DELETE FROM "${d.tableName}" WHERE "_owner_id" = ?`,[this._assertPk(r)],"delete");let p=o[d.fieldName];if(!globalThis.Array.isArray(p)||p.length===0)continue;let h=X(this._assertPk(r),p,d,this._codecs);for(let T of h){let{sql:k,params:D}=H(d.tableName,T);this._executor.exec(k,D,"insert")}}});let u=this._wrap(o);return this._emit("update",{id:r,data:{...e}}),u})}updateWhere(e){return C("repository.updateWhere",{table:this.tableName},()=>{let t=this._record(e.data),n=tt(t,this.meta,this._codecs);if(this._timestampNames.updatedAt&&this._timestampNames.updatedAt in n===!1)n[this._timestampNames.updatedAt]=Date.now();let r=e.includeDeleted?void 0:this.descriptor.softDelete?.column,{sql:s,params:a}=at(this.tableName,n,e.where,r,this.meta),o=this._executor.exec(s,a,"updateWhere");return this._emit("updateWhere",{where:e.where,result:o.changes}),o.changes})}deleteById(e){return C("repository.deleteById",{table:this.tableName},()=>{let t=this.descriptor.primaryKey.name;if(this.descriptor.softDelete){let r=this.descriptor.softDelete.column;return this._executor.exec(`UPDATE "${this.tableName}" SET "${r}" = ? WHERE "${t}" = ?`,[Date.now(),e],"delete"),this._emit("delete",{id:e}),!0}let n=this.db.transaction(()=>{for(let s of this.meta.subTables)this._executor.exec(`DELETE FROM "${s.tableName}" WHERE "_owner_id" = ?`,[e],"delete");return this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${t}" = ?`,[e],"delete").changes>0});return this._emit("delete",{id:e}),n})}deleteWhere(e){return C("repository.deleteWhere",{table:this.tableName},()=>{let t=this.descriptor.primaryKey.name;if(this.descriptor.softDelete){let a=this.descriptor.softDelete.column,{sql:o,params:i}=P(e,a,this.meta),l=`UPDATE "${this.tableName}" SET "${a}" = ? ${o}`.trim(),u=this._executor.exec(l,[Date.now(),...i],"deleteWhere").changes;return this._emit("deleteWhere",{where:e,result:u}),u}let{sql:n,params:r}=P(e,void 0,this.meta),s=this.db.transaction(()=>{for(let i of this.meta.subTables){let l=`DELETE FROM "${i.tableName}" WHERE "_owner_id" IN (SELECT "${t}" FROM "${this.tableName}" ${n})`.trim();this._executor.exec(l,r,"delete")}let a=`DELETE FROM "${this.tableName}" ${n}`.trim();return this._executor.exec(a,r,"delete").changes});return this._emit("deleteWhere",{where:e,result:s}),s})}flush(){C("repository.flush",{table:this.tableName},()=>{this.db.exec(`DELETE FROM "${this.tableName}"`);for(let e of this.meta.subTables)this.db.exec(`DELETE FROM "${e.tableName}"`);this._emit("flush",{})})}drop(){for(let e of this.meta.subTables)this.db.exec(`DROP TABLE IF EXISTS "${e.tableName}"`);this.db.exec(`DROP TABLE IF EXISTS "${this.tableName}"`)}_hydrateOne(e,t,n,r){let s=this.descriptor.primaryKey.name,a=e[s],o=new Map;for(let i of this.meta.subTables){if(t&&!t.includes(i.fieldName)){o.set(i.tableName,[]);continue}let l={tableName:i.tableName,columns:i.columns,subTables:[],columnByName:i.columnByName,columnByPath:i.columnByPath};if(r&&r.has(i.tableName)){let d=r.get(i.tableName).map((p)=>{let h={};for(let T of Object.keys(p))if(T!=="_id"&&T!=="_owner_id"&&T!=="_index")h[T]=p[T];return de(h,l,new Map,this._codecs)});o.set(i.tableName,d);continue}let m=this._executor.all(`SELECT * FROM "${i.tableName}" WHERE "_owner_id" = ? ORDER BY "_index" ASC`,[a],"read").map((c)=>{let d={};for(let p of Object.keys(c))if(p!=="_id"&&p!=="_owner_id"&&p!=="_index")d[p]=c[p];return de(d,l,new Map,this._codecs)});o.set(i.tableName,m)}return de(e,this.meta,o,this._codecs,n,t)}raw(e,...t){return this._executor.all(e,t,"raw")}}class ct{tables;relations=[];constructor(e){this.tables=e}from(e){let t=e;return{scalar:(n)=>({to:(r,s,a)=>{let o={ownerTable:t,ownerField:n,targetTable:r,targetField:s,kind:"scalar",as:a?.as};return this.relations.push(o),o}}),subTable:(n,r)=>({to:(s,a,o)=>{let i={ownerTable:t,ownerField:`${n}.${r}`,targetTable:s,targetField:a,kind:"subTable",as:o?.as};return this.relations.push(i),i}})}}build(){return this.relations}}function Qe(e){return new ct(e)}import{Type as _}from"typebox";import{Compile as z}from"typebox/schema";var Vt=_.Object({key:_.String(),value:_.String(),encoding:_.String(),updatedAt:_.Integer()}),ut=z(Vt),Gt=_.String(),yt=_.Record(_.String(),_.Unknown()),Jt=_.Array(_.String()),Xt=_.Array(_.Object({ownerTable:_.String(),ownerField:_.String(),targetTable:_.String(),targetField:_.String(),kind:_.Union([_.Literal("scalar"),_.Literal("subTable")]),as:_.Optional(_.String())})),Yt=_.String(),br=z(Gt),dt=z(yt),mt=z(Jt),pt=z(Xt),Tr=z(Yt),qe="plain",ft="json",ht="deflate-base64";class ${db;static KEY_SCHEMA_HASH="schemaHash";static KEY_SCHEMA_JSON="schemaJSON";static KEY_TABLES="tables";static KEY_RELATIONS="relations";static KEY_VERSION="version";constructor(e){this.db=e,this.db.exec(`
|
|
9
13
|
CREATE TABLE IF NOT EXISTS _foxdb_meta (
|
|
10
14
|
key TEXT PRIMARY KEY,
|
|
11
15
|
value TEXT NOT NULL,
|
|
12
16
|
encoding TEXT NOT NULL,
|
|
13
17
|
updatedAt INTEGER NOT NULL
|
|
14
18
|
)
|
|
15
|
-
`)}getRow(
|
|
19
|
+
`)}getRow(e){let n=this.db.prepare("SELECT key, value, encoding, updatedAt FROM _foxdb_meta WHERE key = ?").get(e);if(n==null)return null;try{return ut.Parse(n)}catch{let[,r]=ut.Errors(n);throw Error(`MetaStore: row validation failed for key "${e}". Errors: ${JSON.stringify(r)}`)}}setRow(e,t,n){this.db.prepare(`
|
|
16
20
|
INSERT INTO _foxdb_meta (key, value, encoding, updatedAt)
|
|
17
21
|
VALUES (?, ?, ?, ?)
|
|
18
22
|
ON CONFLICT (key) DO UPDATE SET
|
|
19
23
|
value = excluded.value,
|
|
20
24
|
encoding = excluded.encoding,
|
|
21
25
|
updatedAt = excluded.updatedAt
|
|
22
|
-
`).run(
|
|
23
|
-
${
|
|
26
|
+
`).run(e,t,n,Date.now())}getValidatedJSON(e,t,n){let r=JSON.parse(n);if(!t.Check(r)){let[,s]=t.Errors(r);throw Error(`MetaStore: JSON validation failed for key "${e}". Errors: ${JSON.stringify(s)}`)}return r}validateAndSetJSON(e,t,n){if(!t.Check(n)){let[,r]=t.Errors(n);throw Error(`MetaStore: JSON validation failed for key "${e}" before write. Errors: ${JSON.stringify(r)}`)}this.setRow(e,JSON.stringify(n),ft)}getString(e){let t=this.getRow(e);if(t==null)return null;return t.value}setString(e,t){this.setRow(e,t,qe)}getJSON(e){let t=this.getRow(e);if(t==null)return null;try{return JSON.parse(t.value)}catch{return null}}setJSON(e,t){this.setRow(e,JSON.stringify(t),ft)}getCompressed(e){let t=this.getRow(e);if(t==null)return null;if(t.encoding!==ht)return null;let n=Uint8Array.fromBase64(t.value);return Bun.inflateSync(n)}setCompressed(e,t){let n=new Uint8Array(t),s=Bun.deflateSync(n).toBase64();this.setRow(e,s,ht)}delete(e){this.db.prepare("DELETE FROM _foxdb_meta WHERE key = ?").run(e)}getSchemaHash(){let e=this.getRow($.KEY_SCHEMA_HASH);if(e==null)return null;return e.value}setSchemaHash(e){this.setRow($.KEY_SCHEMA_HASH,e,qe)}getSchemaJSON(){let e=this.getRow($.KEY_SCHEMA_JSON);if(e==null)return null;return this.getValidatedJSON($.KEY_SCHEMA_JSON,dt,e.value)}setSchemaJSON(e){this.validateAndSetJSON($.KEY_SCHEMA_JSON,dt,e)}getTables(){let e=this.getRow($.KEY_TABLES);if(e==null)return null;return this.getValidatedJSON($.KEY_TABLES,mt,e.value)}setTables(e){this.validateAndSetJSON($.KEY_TABLES,mt,e)}getRelations(){let e=this.getRow($.KEY_RELATIONS);if(e==null)return null;return this.getValidatedJSON($.KEY_RELATIONS,pt,e.value)}setRelations(e){this.validateAndSetJSON($.KEY_RELATIONS,pt,e)}getVersion(){let e=this.getRow($.KEY_VERSION);if(e==null)return null;return e.value}setVersion(e){this.setRow($.KEY_VERSION,e,qe)}}function zt(e){return e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_foxdb_%' ORDER BY name").all().map((r)=>r.name)}function Zt(e,t){return e.prepare(`SELECT name, "unique" AS "unique" FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'sqlite_autoindex_%'`).all(t)}function en(e,t){return e.prepare(`PRAGMA index_info("${t}")`).all().map((s)=>s.name).filter((s)=>s!=null)}function gt(e,t){let r=e.prepare(`PRAGMA table_info("${t}")`).all(),s=[];for(let a of Zt(e,t)){let o=en(e,a.name);s.push({name:a.name,unique:a.unique,columns:o})}return{name:t,columns:r,indexes:s}}function je(e){return zt(e).map((n)=>gt(e,n))}function tn(e){return e.toUpperCase().trim()}function bt(e){let t=tn(e);if(t.includes("INT"))return"INTEGER";if(t.includes("CHAR")||t.includes("CLOB")||t.includes("TEXT"))return"TEXT";if(t.includes("BLOB"))return"BLOB";if(t.includes("REAL")||t.includes("FLOA")||t.includes("DOUB"))return"REAL";return"NUMERIC"}function nn(e){return e==="_id"||e==="_owner_id"||e==="_index"}function rn(e,t){return e.columns.find((n)=>n.name===t)}function sn(e,t,n){let r=[...t].sort().join(",");return e.indexes.find((s)=>{if(Boolean(s.unique)!==n)return!1;return[...s.columns].sort().join(",")===r})}function on(e){return e.columns.filter((t)=>t.pk>0).sort((t,n)=>t.pk-n.pk).map((t)=>t.name)}function Fe(e,t){let n=[],r=[],s=new Map(t.map((o)=>[o.name,o]));for(let o of e){let i=s.get(o.name);if(!i){if(o.name.includes("__"))n.push({kind:"add-subtable",table:o.name.split("__")[0],subTable:{fieldName:o.name.split("__")[1],tableName:o.name,columns:o.columns.map((c)=>({name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional}))}});else n.push({kind:"add-table",table:o.name});continue}for(let c of o.columns){let d=rn(i,c.name);if(!d){if(c.nullable)n.push({kind:"add-column",table:o.name,column:{name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional},hasDefault:!1});else r.push({kind:"add-column",table:o.name,column:{name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional},hasDefault:!1});continue}if(bt(c.sqlType)!==bt(d.type))r.push({kind:"change-type",table:o.name,column:c.name,from:d.type,to:c.sqlType});let p=!c.nullable,h=d.notnull===1;if(p!==h)if(h&&!p)n.push({kind:"change-nullable",table:o.name,column:c.name,to:!0});else r.push({kind:"change-nullable",table:o.name,column:c.name,to:!1})}for(let c of i.columns){if(nn(c.name))continue;if(!o.columns.find((d)=>d.name===c.name))r.push({kind:"drop-column",table:o.name,column:c.name})}let l=on(i),u=o.primaryKey.split(",").map((c)=>c.trim());if(l.length!==u.length||!l.every((c,d)=>c===u[d]))r.push({kind:"change-pk",table:o.name});let m=i.indexes.filter((c)=>!c.name.startsWith("sqlite_")&&!c.name.startsWith("idx_sqlite_"));for(let c of o.indexes)if(!sn(i,c.columns,c.unique??!1))n.push({kind:"add-index",table:o.name,index:{name:c.name??`idx_${o.name}__${c.columns.join("_")}`,unique:c.unique?1:0,columns:c.columns}});for(let c of m)if(!o.indexes.some((p)=>{let h=[...p.columns].sort().join(","),T=[...c.columns].sort().join(",");return h===T&&Boolean(p.unique)===Boolean(c.unique)}))r.push({kind:"drop-index",table:o.name,index:{name:c.name,unique:c.unique,columns:c.columns}})}let a=new Set(e.map((o)=>o.name));for(let o of t)if(!a.has(o.name))r.push({kind:"drop-table",table:o.name});return{safe:n,unsafe:r}}function We(e,t){return e.find((n)=>n.name===t)}function an(e){let t=e.columns.map((n)=>{let r=!n.nullable?" NOT NULL":"",s=n.name===e.primaryKey?" PRIMARY KEY":"";return` "${n.name}" ${n.sqlType}${s}${r}`});return`CREATE TABLE IF NOT EXISTS "${e.name}" (
|
|
27
|
+
${t.join(`,
|
|
24
28
|
`)}
|
|
25
|
-
)`}function
|
|
26
|
-
${
|
|
29
|
+
)`}function ln(e,t){let n=!t.nullable?" NOT NULL":"";return`ALTER TABLE "${e}" ADD COLUMN "${t.name}" ${t.sqlType}${n}`}function cn(e,t){let n=t.unique?"UNIQUE ":"",r=t.columns.map((s)=>`"${s}"`).join(", ");return`CREATE ${n}INDEX IF NOT EXISTS "${t.name}" ON "${e}" (${r})`}function un(e,t){let n=`${t.name}_foxdb_temp`,r=t.columns.map((s)=>{let a=!s.nullable?" NOT NULL":"",o=s.name===t.primaryKey?" PRIMARY KEY":"";return` "${s.name}" ${s.sqlType}${o}${a}`});e.transaction(()=>{e.exec(`CREATE TABLE "${n}" (
|
|
30
|
+
${r.join(`,
|
|
27
31
|
`)}
|
|
28
|
-
)`);let
|
|
29
|
-
${
|
|
32
|
+
)`);let s=t.columns.map((a)=>`"${a.name}"`).join(", ");e.exec(`INSERT INTO "${n}" (${s}) SELECT ${s} FROM "${t.name}"`),e.exec(`DROP TABLE "${t.name}"`),e.exec(`ALTER TABLE "${n}" RENAME TO "${t.name}"`)})}function dn(e,t,n){let{table:r,subTable:s}=n,a=We(t,r);if(!a)throw Error(`foxdb sync: cannot find owner table "${r}" for sub-table "${s.tableName}"`);let l=[' "_id" INTEGER PRIMARY KEY AUTOINCREMENT',` "_owner_id" ${a.columns.find((u)=>u.name===a.primaryKey)?.sqlType??"TEXT"} NOT NULL`,' "_index" INTEGER NOT NULL',...s.columns.map((u)=>{let m=!u.nullable?" NOT NULL":"";return` "${u.name}" ${u.sqlType}${m}`})];e.transaction(()=>{e.exec(`CREATE TABLE IF NOT EXISTS "${s.tableName}" (
|
|
33
|
+
${l.join(`,
|
|
30
34
|
`)}
|
|
31
|
-
)`),
|
|
32
|
-
`+
|
|
33
|
-
`));return}if(
|
|
35
|
+
)`),e.exec(`CREATE INDEX IF NOT EXISTS "idx_${s.tableName}__owner" ON "${s.tableName}" ("_owner_id")`)})}function Ke(e,t,n){for(let r of e.safe)switch(r.kind){case"add-table":{let s=We(n,r.table);if(!s)throw Error(`foxdb sync: missing desired schema for table "${r.table}"`);t.exec(an(s));break}case"add-subtable":{dn(t,n,r);break}case"add-column":{if(!r.column.nullable)throw Error(`foxdb sync: cannot auto-apply required column "${r.column.name}" without default. Use a migration.`);t.exec(ln(r.table,r.column));break}case"add-index":{t.exec(cn(r.table,r.index));break}case"change-nullable":{if(!r.to)throw Error(`foxdb sync: cannot auto-apply nullable \u2192 NOT NULL change on "${r.table}.${r.column}". Use a migration.`);let s=We(n,r.table);if(!s)throw Error(`foxdb sync: missing desired schema for table "${r.table}"`);un(t,s);break}case"drop-index":{t.exec(`DROP INDEX IF EXISTS "${r.index.name}"`);break}}}function mn(e,t,n){if(e.unsafe.length===0&&e.safe.length===0)return!0;if(n==="ignore")return!0;if(n==="warn"){if(e.unsafe.length>0){console.warn(`[foxdb] ${e.unsafe.length} unsafe schema change(s) detected:`);for(let r of e.unsafe)console.warn(` - ${r.kind}: ${JSON.stringify(r)}`)}return!0}if(n==="error"){if(e.unsafe.length>0||e.safe.length>0)throw Error(`foxdb sync: schema drift detected. Safe=${e.safe.length}, Unsafe=${e.unsafe.length}`);return!0}if(n==="auto")return!0;if(typeof n==="function")return n(e,t)!==!1;return!0}function Ue(e,t,n,r){if(e.safe.length===0&&e.unsafe.length===0)return;if(!mn(e,t,n))return;if(n==="auto"){if(Ke(e,t,r),e.unsafe.length>0)throw Error(`foxdb sync: ${e.unsafe.length} unsafe change(s) cannot be auto-applied. Use migrations.
|
|
36
|
+
`+e.unsafe.map((a)=>` - ${a.kind}: ${JSON.stringify(a)}`).join(`
|
|
37
|
+
`));return}if(n==="ignore")return;if(n==="warn"||n==="error"){if(e.unsafe.length===0)Ke(e,t,r);return}if(typeof n==="function"){if(e.unsafe.length===0)Ke(e,t,r);return}}import{readdirSync as pn,existsSync as fn}from"fs";import{join as hn,resolve as yn}from"path";function gn(e){e.exec(`
|
|
34
38
|
CREATE TABLE IF NOT EXISTS "_foxdb_migrations" (
|
|
35
39
|
"name" TEXT PRIMARY KEY,
|
|
36
40
|
"appliedAt" INTEGER NOT NULL
|
|
37
41
|
)
|
|
38
|
-
`)}function g$(A){let X=A.prepare('SELECT "name" FROM "_foxdb_migrations"').all();return new Set(X.map((Z)=>Z.name))}function k$(A,$){A.prepare('INSERT INTO "_foxdb_migrations" ("name", "appliedAt") VALUES (?, ?)').run($,Date.now())}function w$(A){if(!R$(A))return[];return I$(A,{withFileTypes:!0}).filter((Z)=>Z.isFile()&&Z.name.endsWith(".ts")).map((Z)=>({name:Z.name.slice(0,-3),path:N$(x$(A,Z.name))})).sort((Z,Y)=>Z.name.localeCompare(Y.name))}async function e(A){let $=new f({path:A.path});try{S$($);let X=g$($),Y=w$(A.migrationsDir).filter((G)=>!X.has(G.name));if(Y.length===0)return;for(let G of Y){if(A.target&&G.name>A.target)break;let Q=(await import(G.path)).default;if(!Q)throw Error(`foxdb migrate: file "${G.path}" does not export a default Migration`);if(typeof Q.up!=="function")throw Error(`foxdb migrate: migration "${Q.name}" is missing an up() function`);$.transaction(()=>{Q.up($),k$($,G.name)})}}finally{$.close()}}class AA{listeners=new Map;tableActive=new Set;has(A){let $=this.listeners.get(A);return $!==void 0&&$.size>0}hasAny(A){return this.tableActive.has(A)}on(A,$){if(!this.listeners.has(A))this.listeners.set(A,new Set);this.listeners.get(A).add($);let X=A.split(".")[0];if(X&&X!=="*")this.tableActive.add(X);return()=>{let Z=this.listeners.get(A);if(Z){if(Z.delete($),Z.size===0)this.listeners.delete(A)}}}emit(A,$){let X=this.listeners.get(A);if(X)for(let Y of X)try{Y($)}catch(G){console.error(`[foxdb] event listener error for "${A}":`,G)}let Z=A.indexOf(".");if(Z>0){let G=`${A.slice(0,Z)}.*`,H=this.listeners.get(G);if(H)for(let Q of H)try{Q($)}catch(_){console.error(`[foxdb] event listener error for "${G}":`,_)}}}emitIf(A,$){let X=A.indexOf("."),Z=X>0&&this.has(`${A.slice(0,X)}.*`);if(this.has(A)||Z)this.emit(A,$)}}function v$(A){return typeof A==="object"&&A!==null&&"then"in A&&typeof A.then==="function"}function $A(A,$,X){for(let Z of A)try{let Y=Z($);if(Y&&v$(Y))Y.catch((G)=>{console.error(`[foxdb] async ${X} hook error:`,G)})}catch(Y){console.error(`[foxdb] ${X} hook error:`,Y)}}class XA{startHooks=[];readyHooks=[];shutdownHooks=[];exitHooks=[];_ready=!1;_shutdown=!1;get isReady(){return this._ready}get isShutdown(){return this._shutdown}onStart(A){this.startHooks.push(A)}onReady(A){this.readyHooks.push(A)}onShutdown(A){this.shutdownHooks.push(A)}onExit(A){this.exitHooks.push(A)}runStart(A){$A(this.startHooks,A,"onStart")}runReady(A){$A(this.readyHooks,A,"onReady"),this._ready=!0}runShutdown(A){if(this._shutdown)return;this._shutdown=!0,$A(this.shutdownHooks,A,"onShutdown")}runExit(A){$A(this.exitHooks,A,"onExit")}}function y$(A){let $=A.path??":memory:";if(A.rebuildOnLaunch&&$!==":memory:"&&$.length>0)o($);let X=new f(A),Z,Y=new AA;try{let BA=function(W,F){let L=K.filter((U)=>U.ownerTable===W);if(L.length===0)return F;let z={};for(let[U,B]of Object.entries(F))z[U]=B;let D=L.filter((U)=>U.kind==="scalar");if(D.length>0){let U=new Proxy({},{get(B,V){let M=D.find((P)=>P.as===V||P.ownerField===V);if(!M)return;let I=H.get(M.targetTable);if(!I)return null;let q=F[M.ownerField];if(q==null)return null;return I.raw(`SELECT * FROM "${M.targetTable}" WHERE "${M.targetField}" = ? LIMIT 1`,q)[0]??null}});Object.defineProperty(z,"related",{value:U,writable:!1,enumerable:!1,configurable:!1});for(let B of D)if(B.as)Object.defineProperty(z,B.as,{get(){return z.related[B.as]},enumerable:!1,configurable:!1})}let S=L.filter((U)=>U.kind==="subTable");for(let U of S){let[B,V]=U.ownerField.split("."),M=z[B];if(!globalThis.Array.isArray(M))continue;let I=H.get(U.targetTable);if(!I)continue;let q=M.map((P)=>P[V]).filter((P)=>P!=null),y=new Map;if(q.length>0){let P=q.map(()=>"?").join(", "),R=I.raw(`SELECT * FROM "${U.targetTable}" WHERE "${U.targetField}" IN (${P})`,...q);y=new Map(R.map((g)=>[g[U.targetField],g]))}z[B]=M.map((P)=>{let R=y.get(P[V])??null,g=Object.create(null);Object.assign(g,P);let w=new Proxy({},{get(ZA,h){if(h===U.as||h===U.ownerField)return R;return}});if(Object.defineProperty(g,"related",{value:w,writable:!1,enumerable:!1,configurable:!1}),U.as)Object.defineProperty(g,U.as,{value:R,writable:!1,enumerable:!1,configurable:!1});return g})}return z},EA=function(W,F){if(F.length===0)return[];let L=K.filter((U)=>U.ownerTable===W);if(L.length===0)return F;let z=F.map((U)=>{let B=Object.getPrototypeOf(U),V=B?Object.create(B):{};return Object.assign(V,U),V}),D=L.filter((U)=>U.kind==="scalar"),S=L.filter((U)=>U.kind==="subTable");for(let U of D){let B=H.get(U.targetTable);if(!B)continue;let V=U.ownerField,M=[...new Set(z.map((P)=>P[V]).filter((P)=>P!==null&&P!==void 0))];if(M.length===0)continue;let I=M.map(()=>"?").join(", "),q=B.raw(`SELECT * FROM "${U.targetTable}" WHERE "${U.targetField}" IN (${I})`,...M),y=new Map(q.map((P)=>[P[U.targetField],P]));for(let P of z){let R=y.get(P[V]);if(R)Object.defineProperty(P,`_${V}_resolved`,{value:R,writable:!1,enumerable:!1,configurable:!1})}}for(let U of S){let B=H.get(U.targetTable);if(!B)continue;let[V,M]=U.ownerField.split("."),I=[...new Set(z.flatMap((R)=>{let g=R[V];if(!globalThis.Array.isArray(g))return[];return g.map((w)=>w[M]).filter((w)=>w!==null&&w!==void 0)}))];if(I.length===0)continue;let q=I.map(()=>"?").join(", "),y=B.raw(`SELECT * FROM "${U.targetTable}" WHERE "${U.targetField}" IN (${q})`,...I),P=new Map(y.map((R)=>[R[U.targetField],R]));for(let R of z){let g=R[V];if(!globalThis.Array.isArray(g))continue;R[V]=g.map((w)=>{let ZA=P.get(w[M])??null,h=Object.create(null);Object.assign(h,w);let mA=new Proxy({},{get(a$,VA){if(VA===U.as||VA===U.ownerField)return ZA;return}});if(Object.defineProperty(h,"related",{value:mA,writable:!1,enumerable:!1,configurable:!1}),U.as)Object.defineProperty(h,U.as,{value:ZA,writable:!1,enumerable:!1,configurable:!1});return h})}}if(D.length>0)for(let U of z){let B=new Proxy({},{get(V,M){let I=D.find((q)=>q.as===M||q.ownerField===M);if(!I)return;return U[`_${I.ownerField}_resolved`]??null}});Object.defineProperty(U,"related",{value:B,writable:!1,enumerable:!1,configurable:!1});for(let V of D)if(V.as)Object.defineProperty(U,V.as,{get(){return U[`_${V.ownerField}_resolved`]??null},enumerable:!1,configurable:!1})}return z},yA=function(W){for(let F of H.values())F.flush();if(W?.includeMeta)for(let F of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])J.delete(F)},bA=function(){if(Q.runShutdown(_),A.flushOnExit)for(let F of A.flushOnExit)H.get(F)?.flush();if(A.dropOnExit)for(let F of A.dropOnExit)H.get(F)?.drop();if(A.flushMetaOnExit)for(let F of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])J.delete(F);X.close(),Q.runExit(_),Y.emit("exit",{phase:"exit",timestamp:Date.now()});let W=A.unlinkDbFilesOnExit;if(W===!0||W==="onlyGraceful")o($)},G=Object.entries(A.tables);if(G.length===0)O("NO_TABLES","foxdb: at least one table must be defined in `tables`");let H=new Map;for(let[W,F]of G){let L=m(W,F.schema),z=new Set(L.columns.map((U)=>U.name)),D=F.primaryKey.name;if(!z.has(D))O("INVALID_PK",`foxdb: primary key "${D}" is not a scalar column in table "${W}"`,{table:W,column:D});for(let U of F.indexes??[])for(let B of U.columns)if(!z.has(B.name))O("INVALID_INDEX",`foxdb: index column "${B.name}" not found in table "${W}"`,{table:W,column:B.name});let S=new a(W,F,X);H.set(W,S)}for(let[W,F]of H)F.setEventBus(Y);let Q=new XA;if(A.onStart)Q.onStart(A.onStart);if(A.onReady)Q.onReady(A.onReady);if(A.onShutdown)Q.onShutdown(A.onShutdown);if(A.onExit)Q.onExit(A.onExit);let _,K=[];if(typeof A.relations==="function"){let W=WA(A.tables),F=A.relations(W);for(let L of F)K.push(L)}else for(let[W,F]of Object.entries(A.relations??{})){if(!F)continue;let L=H.get(W);if(!L)O("INVALID_RELATION",`foxdb: relation owner table "${W}" not found in tables`,{table:W});for(let z of F){let D=H.get(z.targetTableName);if(!D)O("INVALID_RELATION",`foxdb: relation target table "${z.targetTableName}" not found in tables`,{table:z.targetTableName});let S=z.ownerField.split(".");if(S.length===1){let[B=""]=S;if(!new Set(L.meta.columns.map((M)=>M.name)).has(B))O("INVALID_RELATION",`foxdb: relation ownerField "${z.ownerField}" is not a scalar column in table "${W}"`,{table:W,field:z.ownerField})}else if(S.length===2){let[B="",V=""]=S,M=L.meta.subTables.find((q)=>q.fieldName===B);if(!M)O("INVALID_RELATION",`foxdb: relation ownerField "${z.ownerField}" references unknown sub-table "${B}" in table "${W}"`,{table:W,field:z.ownerField});if(!new Set(M.columns.map((q)=>q.name)).has(V))O("INVALID_RELATION",`foxdb: relation ownerField "${z.ownerField}" references unknown column "${V}" in sub-table "${B}" of table "${W}"`,{table:W,field:z.ownerField})}else O("INVALID_RELATION",`foxdb: relation ownerField "${z.ownerField}" has too many dot segments (max 2 allowed)`,{table:W,field:z.ownerField});if(!new Set(D.meta.columns.map((B)=>B.name)).has(z.targetField))O("INVALID_RELATION",`foxdb: relation targetField "${z.targetField}" is not a scalar column in table "${z.targetTableName}"`,{table:z.targetTableName,field:z.targetField});K.push({ownerTable:W,ownerField:z.ownerField,targetTable:z.targetTableName,targetField:z.targetField,kind:S.length===1?"scalar":"subTable",as:void 0})}}let C=[];for(let[W,F]of G){let L=m(W,F.schema);C.push({name:W,columns:L.columns,indexes:(F.indexes??[]).map((z)=>({name:z.name,columns:z.columns.map((D)=>D.name),unique:z.unique})),primaryKey:F.primaryKey.name});for(let z of L.subTables)C.push({name:z.tableName,columns:z.columns,indexes:(F.subTables?.[z.fieldName]?.indexes??[]).map((D)=>({name:D.name,columns:D.columns.map((S)=>S.name),unique:D.unique})),primaryKey:"_id"})}let J=new N(X),E=Object.fromEntries(G.map(([W,F])=>[W,F.schema])),T=JSON.stringify(E),k=Bun.hash(T),v=new TextEncoder().encode(T),d=J.getString("_schema_hash"),l=String(k);if(d!==l&&A.sync&&A.sync!=="ignore"){let W=zA(X),F=UA(C,W);KA(F,X,A.sync,C)}J.setString("_schema_hash",l),J.setCompressed("_schema_compressed",v),J.setJSON("_tables",Object.keys(A.tables)),J.setJSON("_relations",K),J.setString("_foxdb_version","0.0.2");let hA={get schemaHash(){return J.getString("_schema_hash")},get schemaJSON(){let W=J.getCompressed("_schema_compressed");return W?new TextDecoder().decode(W):null},get tables(){return J.getJSON("_tables")},get relations(){return J.getJSON("_relations")},get version(){return J.getString("_foxdb_version")}};for(let[W,F]of H){if(K.filter((z)=>z.ownerTable===W).length===0)continue;F.setMaterializer((z)=>BA(W,z),(z)=>EA(W,z))}Z=Object.create(null);for(let W of Object.keys(A.tables))Object.defineProperty(Z,W,{get(){return H.get(W)},enumerable:!0,configurable:!0});let fA=async()=>{if(!A.migrations)O("MIGRATIONS_NOT_CONFIGURED","foxdb: migrations dir not configured. Pass `migrations: { dir: ... }` to createORM().");await e({path:$,migrationsDir:A.migrations.dir})},uA={on(W,F,L){if(typeof F==="string"&&typeof L==="function"){let z=`${W}.${F}`;return Y.on(z,L)}if(typeof F==="function")return Y.on(W,F);O("INVALID_EVENT_LISTENER","foxdb: invalid event listener arguments")}};if(_={orm:Z,db:X,meta:J,tables:Object.keys(A.tables),repos:H,logger:{log:(...W)=>{console.log("[foxdb]",...W)},error:(...W)=>{console.error("[foxdb]",...W)}}},A.unlinkDbFilesOnExit==="any"){let W=()=>{try{o($)}catch{}},F=()=>{Q.runExit(_),W(),process.exit(1)};process.on("exit",W),process.on("SIGINT",F),process.on("SIGTERM",F),process.on("uncaughtException",(L)=>{Y.emit("fail",{phase:"fail",error:L,timestamp:Date.now()}),F()})}if(Object.assign(Z,{_transaction:X.transaction.bind(X),_close:bA,_meta:hA,_materialize:BA,_materializeMany:EA,_flush:yA,_migrate:fA,_events:uA}),Q.runStart(_),A.flushOnStart)for(let W of A.flushOnStart)H.get(W)?.flush();if(A.dropOnStart)for(let W of A.dropOnStart)H.get(W)?.drop();if(A.flushMetaOnStart)for(let W of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])J.delete(W);if(A.autoMigrate&&A.migrations)e({path:$,migrationsDir:A.migrations.dir}).catch((W)=>{console.error("[foxdb] autoMigrate failed:",W)});if(A.seed)A.seed(Z);Q.runReady(_),Y.emit("ready",{phase:"ready",timestamp:Date.now()})}catch(G){if(G instanceof b)Y.emit("fail",{phase:"fail",error:G,timestamp:Date.now()});else{let H=new b(String(G),{code:"UNEXPECTED",trace:HA()});Y.emit("fail",{phase:"fail",error:H,timestamp:Date.now()})}throw G}return Z}import{IsString as h$,IsNumber as f$,IsInteger as u$,IsBoolean as b$,IsLiteral as m$}from"typebox";function n$(A){return h$(A)||f$(A)||u$(A)||b$(A)||m$(A)}function vA(A){let $={};for(let X of Object.keys(A.properties)){let Z=A.properties[X];if(Z&&n$(Z))$[X]={_tag:"ColumnRef",name:X,schema:Z}}return $}function d$(A,$){let X=vA(A),Z=$(X);return{schema:A,...Z}}import{existsSync as p$,mkdirSync as c$,writeFileSync as i$}from"fs";import{join as l$,resolve as o$}from"path";function s$(A,$){return`import type { Migration } from "@xwxfox/foxdb";
|
|
42
|
+
`)}function bn(e){let n=e.prepare('SELECT "name" FROM "_foxdb_migrations"').all();return new Set(n.map((r)=>r.name))}function Tn(e,t){e.prepare('INSERT INTO "_foxdb_migrations" ("name", "appliedAt") VALUES (?, ?)').run(t,Date.now())}function Sn(e){if(!fn(e))return[];return pn(e,{withFileTypes:!0}).filter((r)=>r.isFile()&&r.name.endsWith(".ts")).map((r)=>({name:r.name.slice(0,-3),path:yn(hn(e,r.name))})).sort((r,s)=>r.name.localeCompare(s.name))}async function ye(e){let t=new K({path:e.path});try{gn(t);let n=bn(t),s=Sn(e.migrationsDir).filter((a)=>!n.has(a.name));if(s.length===0)return;for(let a of s){if(e.target&&a.name>e.target)break;let i=(await import(a.path)).default;if(!i)throw Error(`foxdb migrate: file "${a.path}" does not export a default Migration`);if(typeof i.up!=="function")throw Error(`foxdb migrate: migration "${i.name}" is missing an up() function`);t.transaction(()=>{i.up(t),Tn(t,a.name)})}}finally{t.close()}}class ge{listeners=new Map;tableActive=new Set;has(e){let t=this.listeners.get(e);return t!==void 0&&t.size>0}hasAny(e){return this.tableActive.has(e)}on(e,t){if(!this.listeners.has(e))this.listeners.set(e,new Set);this.listeners.get(e).add(t);let n=e.split(".")[0];if(n&&n!=="*")this.tableActive.add(n);return()=>{let r=this.listeners.get(e);if(r){if(r.delete(t),r.size===0)this.listeners.delete(e)}}}emit(e,t){let n=this.listeners.get(e);if(n)for(let s of n)try{s(t)}catch(a){console.error(`[foxdb] event listener error for "${e}":`,a)}let r=e.indexOf(".");if(r>0){let a=`${e.slice(0,r)}.*`,o=this.listeners.get(a);if(o)for(let i of o)try{i(t)}catch(l){console.error(`[foxdb] event listener error for "${a}":`,l)}}}emitIf(e,t){let n=e.indexOf("."),r=n>0&&this.has(`${e.slice(0,n)}.*`);if(this.has(e)||r)this.emit(e,t)}}function Rn(e){return typeof e==="object"&&e!==null&&"then"in e&&typeof e.then==="function"}function be(e,t,n){for(let r of e)try{let s=r(t);if(s&&Rn(s))s.catch((a)=>{console.error(`[foxdb] async ${n} hook error:`,a)})}catch(s){console.error(`[foxdb] ${n} hook error:`,s)}}class Te{startHooks=[];readyHooks=[];shutdownHooks=[];exitHooks=[];_ready=!1;_shutdown=!1;get isReady(){return this._ready}get isShutdown(){return this._shutdown}onStart(e){this.startHooks.push(e)}onReady(e){this.readyHooks.push(e)}onShutdown(e){this.shutdownHooks.push(e)}onExit(e){this.exitHooks.push(e)}runStart(e){be(this.startHooks,e,"onStart")}runReady(e){be(this.readyHooks,e,"onReady"),this._ready=!0}runShutdown(e){if(this._shutdown)return;this._shutdown=!0,be(this.shutdownHooks,e,"onShutdown")}runExit(e){be(this.exitHooks,e,"onExit")}}function wn(e){let t=e.path??":memory:";if(e.rebuildOnLaunch&&t!==":memory:"&&t.length>0)ie(t);let n=new K(e);if(e.autoVacuum==="incremental"&&e.vacuumIntervalMs)n.scheduler.schedule("auto-vacuum",e.vacuumIntervalMs,()=>{try{n.exec("PRAGMA incremental_vacuum(1000);")}catch{}});let r,s=new ge;try{let ae=function(f,b){let w=u.filter((g)=>g.ownerTable===f);if(w.length===0)return b;let y={};for(let[g,S]of Object.entries(b))y[g]=S;let N=w.filter((g)=>g.kind==="scalar");if(N.length>0){let g=new Proxy({},{get(S,R){let x=N.find((E)=>E.as===R||E.ownerField===R);if(!x)return;let M=o.get(x.targetTable);if(!M)return null;let A=b[x.ownerField];if(A==null)return null;return M.raw(`SELECT * FROM "${x.targetTable}" WHERE "${x.targetField}" = ? LIMIT 1`,A)[0]??null}});Object.defineProperty(y,"related",{value:g,writable:!1,enumerable:!1,configurable:!1});for(let S of N)if(S.as)Object.defineProperty(y,S.as,{get(){return y.related[S.as]},enumerable:!1,configurable:!1})}let v=w.filter((g)=>g.kind==="subTable");for(let g of v){let[S,R]=g.ownerField.split("."),x=y[S];if(!globalThis.Array.isArray(x))continue;let M=o.get(g.targetTable);if(!M)continue;let A=x.map((E)=>E[R]).filter((E)=>E!=null),j=new Map;if(A.length>0){let E=A.map(()=>"?").join(", "),I=M.raw(`SELECT * FROM "${g.targetTable}" WHERE "${g.targetField}" IN (${E})`,...A);j=new Map(I.map((L)=>[L[g.targetField],L]))}y[S]=x.map((E)=>{let I=j.get(E[R])??null,L=Object.create(null);Object.assign(L,E);let q=new Proxy({},{get(Re,F){if(F===g.as||F===g.ownerField)return I;return}});if(Object.defineProperty(L,"related",{value:q,writable:!1,enumerable:!1,configurable:!1}),g.as)Object.defineProperty(L,g.as,{value:I,writable:!1,enumerable:!1,configurable:!1});return L})}return y},Ve=function(f,b){if(b.length===0)return[];let w=u.filter((g)=>g.ownerTable===f);if(w.length===0)return b;let y=b.map((g)=>{let S=Object.getPrototypeOf(g),R=S?Object.create(S):{};return Object.assign(R,g),R}),N=w.filter((g)=>g.kind==="scalar"),v=w.filter((g)=>g.kind==="subTable");for(let g of N){let S=o.get(g.targetTable);if(!S)continue;let R=g.ownerField,x=[...new Set(y.map((E)=>E[R]).filter((E)=>E!==null&&E!==void 0))];if(x.length===0)continue;let M=x.map(()=>"?").join(", "),A=S.raw(`SELECT * FROM "${g.targetTable}" WHERE "${g.targetField}" IN (${M})`,...x),j=new Map(A.map((E)=>[E[g.targetField],E]));for(let E of y){let I=j.get(E[R]);if(I)Object.defineProperty(E,`_${R}_resolved`,{value:I,writable:!1,enumerable:!1,configurable:!1})}}for(let g of v){let S=o.get(g.targetTable);if(!S)continue;let[R,x]=g.ownerField.split("."),M=[...new Set(y.flatMap((I)=>{let L=I[R];if(!globalThis.Array.isArray(L))return[];return L.map((q)=>q[x]).filter((q)=>q!==null&&q!==void 0)}))];if(M.length===0)continue;let A=M.map(()=>"?").join(", "),j=S.raw(`SELECT * FROM "${g.targetTable}" WHERE "${g.targetField}" IN (${A})`,...M),E=new Map(j.map((I)=>[I[g.targetField],I]));for(let I of y){let L=I[R];if(!globalThis.Array.isArray(L))continue;I[R]=L.map((q)=>{let Re=E.get(q[x])??null,F=Object.create(null);Object.assign(F,q);let _t=new Proxy({},{get(Dn,Ge){if(Ge===g.as||Ge===g.ownerField)return Re;return}});if(Object.defineProperty(F,"related",{value:_t,writable:!1,enumerable:!1,configurable:!1}),g.as)Object.defineProperty(F,g.as,{value:Re,writable:!1,enumerable:!1,configurable:!1});return F})}}if(N.length>0)for(let g of y){let S=new Proxy({},{get(R,x){let M=N.find((A)=>A.as===x||A.ownerField===x);if(!M)return;return g[`_${M.ownerField}_resolved`]??null}});Object.defineProperty(g,"related",{value:S,writable:!1,enumerable:!1,configurable:!1});for(let R of N)if(R.as)Object.defineProperty(g,R.as,{get(){return g[`_${R.ownerField}_resolved`]??null},enumerable:!1,configurable:!1})}return y},Rt=function(f){for(let b of o.values())b.flush();if(f?.includeMeta)for(let b of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])c.delete(b)},Ot=function(){if(i.runShutdown(l),e.flushOnExit)for(let b of e.flushOnExit)o.get(b)?.flush();if(e.dropOnExit)for(let b of e.dropOnExit)o.get(b)?.drop();if(e.flushMetaOnExit)for(let b of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])c.delete(b);n.close(),i.runExit(l),s.emit("exit",{phase:"exit",timestamp:Date.now()});let f=e.unlinkDbFilesOnExit;if(f===!0||f==="onlyGraceful")ie(t)},a=Object.entries(e.tables);if(a.length===0)O("NO_TABLES","foxdb: at least one table must be defined in `tables`");let o=new Map;for(let[f,b]of a){let w=J(f,b.schema,ne(b.generated)),y=new Set(w.columns.map((g)=>g.name)),N=b.primaryKey.name;if(!y.has(N))O("INVALID_PK",`foxdb: primary key "${N}" is not a scalar column in table "${f}"`,{table:f,column:N});for(let g of b.indexes??[])for(let S of g.columns)if(!y.has(S.name))O("INVALID_INDEX",`foxdb: index column "${S.name}" not found in table "${f}"`,{table:f,column:S.name});let v=new he(f,b,n);o.set(f,v)}for(let[f,b]of o)b.setEventBus(s);if(e.hooks?.onQuery)for(let f of o.values())f.setMetricsHook(e.hooks.onQuery);let i=new Te;if(e.onStart)i.onStart(e.onStart);if(e.onReady)i.onReady(e.onReady);if(e.onShutdown)i.onShutdown(e.onShutdown);if(e.onExit)i.onExit(e.onExit);let l,u=[];if(typeof e.relations==="function"){let f=Qe(e.tables),b=e.relations(f);for(let w of b)u.push(w)}else for(let[f,b]of Object.entries(e.relations??{})){if(!b)continue;let w=o.get(f);if(!w)O("INVALID_RELATION",`foxdb: relation owner table "${f}" not found in tables`,{table:f});for(let y of b){let N=o.get(y.targetTableName);if(!N)O("INVALID_RELATION",`foxdb: relation target table "${y.targetTableName}" not found in tables`,{table:y.targetTableName});let v=y.ownerField.split(".");if(v.length===1){let[S=""]=v;if(!new Set(w.meta.columns.map((x)=>x.name)).has(S))O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" is not a scalar column in table "${f}"`,{table:f,field:y.ownerField})}else if(v.length===2){let[S="",R=""]=v,x=w.meta.subTables.find((A)=>A.fieldName===S);if(!x)O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" references unknown sub-table "${S}" in table "${f}"`,{table:f,field:y.ownerField});if(!new Set(x.columns.map((A)=>A.name)).has(R))O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" references unknown column "${R}" in sub-table "${S}" of table "${f}"`,{table:f,field:y.ownerField})}else O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" has too many dot segments (max 2 allowed)`,{table:f,field:y.ownerField});if(!new Set(N.meta.columns.map((S)=>S.name)).has(y.targetField))O("INVALID_RELATION",`foxdb: relation targetField "${y.targetField}" is not a scalar column in table "${y.targetTableName}"`,{table:y.targetTableName,field:y.targetField});u.push({ownerTable:f,ownerField:y.ownerField,targetTable:y.targetTableName,targetField:y.targetField,kind:v.length===1?"scalar":"subTable",as:void 0})}}let m=[];for(let[f,b]of a){let w=J(f,b.schema,ne(b.generated));m.push({name:f,columns:w.columns,indexes:(b.indexes??[]).map((y)=>({name:y.name,columns:y.columns.map((N)=>N.name),unique:y.unique})),primaryKey:b.primaryKey.name});for(let y of w.subTables)m.push({name:y.tableName,columns:y.columns,indexes:(b.subTables?.[y.fieldName]?.indexes??[]).map((N)=>({name:N.name,columns:N.columns.map((v)=>v.name),unique:N.unique})),primaryKey:"_id"})}let c=new $(n),d=Object.fromEntries(a.map(([f,b])=>[f,b.schema])),p=JSON.stringify(d),h=Bun.hash(p),T=new TextEncoder().encode(p),k=c.getString("_schema_hash"),D=String(h);if(k!==D&&e.sync&&e.sync!=="ignore"){let f=je(n),b=Fe(m,f);Ue(b,n,e.sync,m)}c.setString("_schema_hash",D),c.setCompressed("_schema_compressed",T),c.setJSON("_tables",Object.keys(e.tables)),c.setJSON("_relations",u),c.setString("_foxdb_version","0.0.2");let wt={get schemaHash(){return c.getString("_schema_hash")},get schemaJSON(){let f=c.getCompressed("_schema_compressed");return f?new TextDecoder().decode(f):null},get tables(){return c.getJSON("_tables")},get relations(){return c.getJSON("_relations")},get version(){return c.getString("_foxdb_version")}};for(let[f,b]of o){if(u.filter((y)=>y.ownerTable===f).length===0)continue;b.setMaterializer((y)=>ae(f,y),(y)=>Ve(f,y))}r=Object.create(null);for(let f of Object.keys(e.tables))Object.defineProperty(r,f,{get(){return o.get(f)},enumerable:!0,configurable:!0});let xt=async()=>{if(!e.migrations)O("MIGRATIONS_NOT_CONFIGURED","foxdb: migrations dir not configured. Pass `migrations: { dir: ... }` to createORM().");await ye({path:t,migrationsDir:e.migrations.dir})},Et={on(f,b,w){if(typeof b==="string"&&typeof w==="function"){let y=`${f}.${b}`;return s.on(y,w)}if(typeof b==="function")return s.on(f,b);O("INVALID_EVENT_LISTENER","foxdb: invalid event listener arguments")}};if(e.bulkLoadMode)n.setSynchronous("OFF");if(l={orm:r,db:n,meta:c,tables:Object.keys(e.tables),repos:o,logger:{log:(...f)=>{console.log("[foxdb]",...f)},error:(...f)=>{console.error("[foxdb]",...f)}}},e.unlinkDbFilesOnExit==="any"){let f=()=>{try{ie(t)}catch{}},b=()=>{i.runExit(l),f(),process.exit(1)};process.on("exit",f),process.on("SIGINT",b),process.on("SIGTERM",b),process.on("uncaughtException",(w)=>{s.emit("fail",{phase:"fail",error:w,timestamp:Date.now()}),b()})}if(Object.assign(r,{_transaction:n.transaction.bind(n),_close:Ot,_setBulkLoadMode(f){n.setSynchronous(f?"OFF":"NORMAL")},_meta:wt,_materialize:ae,_materializeMany:Ve,_flush:Rt,_migrate:xt,_events:Et}),i.runStart(l),e.flushOnStart)for(let f of e.flushOnStart)o.get(f)?.flush();if(e.dropOnStart)for(let f of e.dropOnStart)o.get(f)?.drop();if(e.flushMetaOnStart)for(let f of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])c.delete(f);if(e.autoMigrate&&e.migrations)ye({path:t,migrationsDir:e.migrations.dir}).catch((f)=>{console.error("[foxdb] autoMigrate failed:",f)});if(e.seed)e.seed(r);i.runReady(l),s.emit("ready",{phase:"ready",timestamp:Date.now()})}catch(a){if(a instanceof G)s.emit("fail",{phase:"fail",error:a,timestamp:Date.now()});else{let o=new G(String(a),{code:"UNEXPECTED",trace:_e()});s.emit("fail",{phase:"fail",error:o,timestamp:Date.now()})}throw a}return r}import{IsString as xn,IsNumber as En,IsInteger as On,IsBoolean as _n,IsLiteral as Nn,IsObject as Tt,IsOptional as kn}from"typebox";function He(e){return xn(e)||En(e)||On(e)||_n(e)||Nn(e)}function Se(e){if(kn(e)){let t=e,n={};for(let r of Object.keys(t)){if(r==="~optional")continue;n[r]=t[r]}return n}return e}function St(e){let t={};for(let n of Object.keys(e.properties)){let r=e.properties[n];if(r&&He(r))t[n]={_tag:"ColumnRef",name:n,schema:r};if(r){let s=Se(r);if(s&&Tt(s)){let o=s.properties;for(let i of Object.keys(o)){let l=o[i];if(l){let u=Se(l);if(He(u)){let c=`${n}__${i}`;t[c]={_tag:"ColumnRef",name:c,schema:u}}let m=Se(l);if(m&&Tt(m)){let d=m.properties;for(let p of Object.keys(d)){let h=d[p];if(h){let T=Se(h);if(He(T)){let k=`${n}__${i}__${p}`;t[k]={_tag:"ColumnRef",name:k,schema:T}}}}}}}}}}return t}function Cn(e,t){let n=St(e),r=t(n);return{schema:e,...r}}import{existsSync as An,mkdirSync as $n,writeFileSync as Mn}from"fs";import{join as In,resolve as vn}from"path";function Ln(e,t){return`import type { Migration } from "@xwxfox/foxdb";
|
|
39
43
|
|
|
40
44
|
export default {
|
|
41
|
-
name: "${
|
|
42
|
-
date: "${
|
|
45
|
+
name: "${e}",
|
|
46
|
+
date: "${t}",
|
|
43
47
|
|
|
44
48
|
up(db) {
|
|
45
49
|
// Your migration logic here
|
|
46
50
|
},
|
|
47
51
|
} satisfies Migration;
|
|
48
|
-
`}function
|
|
52
|
+
`}function Bn(e,t){if(!An(t))$n(t,{recursive:!0});let n=new Date,r=n.getFullYear(),s=String(n.getMonth()+1).padStart(2,"0"),a=String(n.getDate()).padStart(2,"0"),o=String(n.getHours()).padStart(2,"0"),i=String(n.getMinutes()).padStart(2,"0"),l=String(n.getSeconds()).padStart(2,"0"),m=`${`${r}${s}${a}_${o}${i}${l}`}_${e}.ts`,c=vn(In(t,m)),d=n.toISOString(),p=Ln(e,d);return Mn(c,p,"utf-8"),c}export{C as withTrace,Cn as table,Pe as resolveTimestampNames,O as raise,ye as migrate,J as introspectTable,gt as inspectSchema,je as inspectAllTables,Qe as createRelationBuilder,wn as createORM,Bn as createMigration,Fe as computeDiff,Ie as buildCreateTableSQL,Ue as applySync,yt as SchemaJSONSchema,he as Repository,G as ORMError,$ as MetaStore,Te as LifecycleManager,ge as EventBus,De as DEFAULT_TIMESTAMP_NAMES,K as BunDatabase,fe as BatchWriter};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xwxfox/foxdb",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "itty bitty e2e typed orm for bun :3",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"publishConfig": {
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"scripts": {
|
|
11
11
|
"build": "bunup",
|
|
12
12
|
"docs": "bun run docs.ts",
|
|
13
|
+
"bench": "bun run ./benchmarks/real-world-schema-bench.ts",
|
|
13
14
|
"release": "bun run publish.ts"
|
|
14
15
|
},
|
|
15
16
|
"keywords": [
|
|
@@ -64,4 +65,4 @@
|
|
|
64
65
|
"dependencies": {
|
|
65
66
|
"typebox": "^1.1.34"
|
|
66
67
|
}
|
|
67
|
-
}
|
|
68
|
+
}
|