@lunora/sql-store 1.0.0-alpha.41 → 1.0.0-alpha.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dialect.mjs +0 -1
- package/dist/index.mjs +1 -2
- package/dist/packem_shared/createSqlCtxDb-BXAFW5DJ.mjs +1 -0
- package/dist/packem_shared/decodeBigint-DfiI8pkL.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/createSqlCtxDb-BPEyi1Yl.mjs +0 -1831
- package/dist/packem_shared/decodeBigint-Dedu92k4.mjs +0 -69
package/dist/dialect.mjs
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { decodeBigint, effectiveColumnKind, sqliteDecode, sqliteEncode, tryJsonParse } from './packem_shared/decodeBigint-Dedu92k4.mjs';
|
|
1
|
+
import{createSqlCtxDb as n,decodeGlobalRow as o,readSqlCdcChanges as i,runSqlAggregateMigrations as a,runSqlCdcMigration as l,runSqlGlobalTableMigrations as t,runSqlRankMigrations as d,runSqlSearchMigrations as g,trimSqlCdcChanges as c}from"./packem_shared/createSqlCtxDb-BXAFW5DJ.mjs";import{decodeBigint as s,effectiveColumnKind as S,sqliteDecode as C,sqliteEncode as u,tryJsonParse as M}from"./packem_shared/decodeBigint-DfiI8pkL.mjs";export{n as createSqlCtxDb,s as decodeBigint,o as decodeGlobalRow,S as effectiveColumnKind,i as readSqlCdcChanges,a as runSqlAggregateMigrations,l as runSqlCdcMigration,t as runSqlGlobalTableMigrations,d as runSqlRankMigrations,g as runSqlSearchMigrations,C as sqliteDecode,u as sqliteEncode,c as trimSqlCdcChanges,M as tryJsonParse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{aggregateTableName as Y,rankTableName as J,ftsTableName as xe,hasTrigger as bt,runRowValidators as Ie,assertFlatPredicate as Qe,mergeWhere as q,sortColumnName as G,resolveRankPartition as Ze,encodePartitionKey as Te,decodeCursor as et,RANK_TIEBREAK as ue,CountRlsUnsupportedError as tt,normalizeIdStructurally as Rt,assertValidClientId as St,aggregateSqlFunction as ce,softDeleteScope as de,compileWhereSql as le,normalizeOrderKeys as vt,buildSeekWhere as It,resolveRelationPredicates as it,resolveWith as nt,applySelect as at,encodeCursor as At,NotFoundError as Lt,applyOnDelete as Ot,ConflictError as fe,normalizeCountArgument as Ct,selectIndexForCount as Mt,encodeAggregateKey as P,selectIndexForAggregate as kt,readAggregateValue as Ae,renderSql as ft,runTriggers as Dt,matchesRankStaticWhere as ot,stringifySearchText as ut,selectIndexForGroupBy as xt,fanOutScalarCounts as qt,matchesStaticWhere as Le,coerceAggregateNumber as Oe,foldAggregateTally as Ft,NotUniqueError as Wt,throwingScheduler as Ut,tokenizeSearch as _t,buildFtsMatch as Bt,scoreDocument as jt}from"@lunora/do";import{LunoraError as b}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{sqliteDecode as Ht,sqliteEncode as Pt,effectiveColumnKind as _e}from"./decodeBigint-DfiI8pkL.mjs";const Kt=(a,f)=>{if(a.size<f)return;const s=a.keys().next().value;s!==void 0&&a.delete(s)},Vt=a=>a==="_id"||a==="id"?"id":a,O=a=>e`${e.identifier(Vt(a))}`,Xt=new Set(["_id","id"]),qe=(a,f,s)=>a==="postgres"?e`${f} IS NOT DISTINCT FROM ${s}`:a==="mysql"?e`${f} <=> ${s}`:e`${f} IS ${s}`,Yt=a=>{const f=a.map(s=>e`${O(s.field)} ${e.raw(s.direction==="desc"?"DESC":"ASC")}`);return a.some(s=>Xt.has(s.field))||f.push(e`${O("id")} ASC`),e.join(f,e`, `)},S=(a,f,s)=>{const{params:n,sql:w}=ft(f.name,s);return a.all(w,n)},v=(a,f,s)=>{const{params:n,sql:w}=ft(f.name,s);return a.run(w,n)},ke=async(a,f,s)=>{const n=s.unique?e`UNIQUE `:e``;if(f.name==="mysql"){try{await v(a,f,e`CREATE ${n}INDEX ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)}catch(w){if(w.errno!==1061)throw w}return}await v(a,f,e`CREATE ${n}INDEX IF NOT EXISTS ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)},rt=50,F=Pt,st=new WeakMap,De=a=>{const f=st.get(a);if(f!==void 0)return f;const s=(async()=>{let n;try{await a.run('CREATE VIRTUAL TABLE IF NOT EXISTS "__lunora_fts_probe" USING fts5(x)',[]),n=!0}catch{n=!1}finally{try{await a.run('DROP TABLE IF EXISTS "__lunora_fts_probe"',[])}catch{}}return n})();return st.set(a,s),s},Fe=a=>{const f=[];for(const[s,n]of Object.entries(a.shape)){const w=n._meta?.column;w&&f.push([s,w])}return f},ct=new WeakMap,Gt=a=>{let f=ct.get(a);return f===void 0&&(f=Object.entries(a.shape).map(([s,n])=>[s,_e(n)]),ct.set(a,f)),f},zt=(a,f)=>{const s={};for(const[n,w]of Gt(a)){const c=f[n];c!==void 0&&(s[n]=Ht(c,w))}return s._id=f.id,s._creationTime=f._creationTime,s},K=(a,f)=>f?zt(a,f):null,Jt=(a,f,s)=>{const n={...f};for(const[w,c]of Fe(a)){if(c.serverDefault){n[w]=c.serverDefault({auth:s});continue}n[w]===void 0&&(c.defaultFn?n[w]=c.defaultFn():"defaultValue"in c&&(n[w]=c.defaultValue))}return n},dt=(a,f,s,n)=>{for(const[w,c]of Fe(a)){if(c.serverDefault){w in f&&(s[w]=c.serverDefault({auth:n}));continue}c.onUpdateFn&&!(w in f)&&(s[w]=c.onUpdateFn())}},Qt=128,Zt=()=>{const a=new Map;return{delete:f=>{a.delete(f)},get:f=>{const s=a.get(f);if(s!==void 0)return a.delete(f),a.set(f,s),s},set:(f,s)=>{a.has(f)?a.delete(f):Kt(a,Qt),a.set(f,s)}}},ei=async(a,f,s,n,w)=>{const c=w.get(n);if(c!==void 0)return c;const l=[];for(const[y,R]of Object.entries(s.tables))R.shardMode!==void 0&&R.shardMode.kind!=="global"||l.push(y);const g=await Promise.all(l.map(async y=>({found:(await S(a,f,e`SELECT 1 FROM ${e.identifier(y)} WHERE ${e.identifier("id")} = ${n} LIMIT 1`)).length>0,tableName:y})));for(const y of g)if(y.found)return w.set(n,y.tableName),y.tableName},Q=a=>a==null?null:Number(a),ti=(a,f)=>f.map(s=>{const n={};for(const w of a)n[w]=s[w]??null;return{key:n,value:Q(s.value)}}),We=(a,f)=>{const s=[];for(const n of f){const w=K(a,n);w&&s.push(w)}return s},ii=async(a,f,s,n,w,c)=>{const l=_t(w.query);if(l.length===0)return[];const g=xe(n,w.indexName),y=[e`f.${e.identifier("__text__")} MATCH ${Bt(l)}`];for(const C of w.filters)y.push(e`m.${O(C.field)} = ${F(C.value)}`);s.softDeleteMode&&y.push(e`m.${O(s.softDeleteMode.field)} IS NULL`);let R=e`SELECT m.* FROM ${e.identifier(g)} f JOIN ${e.identifier(n)} m ON m.${e.identifier("id")} = f.${e.identifier("__id__")} WHERE ${e.join(y,e` AND `)} ORDER BY f.rank, m.${e.identifier("_creationTime")} DESC`;typeof c=="number"&&(R=e`${R} LIMIT ${e.raw(String(Math.max(0,Math.floor(c))))}`);const I=await S(a,f,R);return We(s,I)},ni=async(a,f,s,n,w,c)=>{const l=_t(w.query);if(l.length===0)return[];const g=w.filters.map(M=>e`${O(M.field)} = ${F(M.value)}`);s.softDeleteMode&&g.push(e`${O(s.softDeleteMode.field)} IS NULL`);let y=e`SELECT * FROM ${e.identifier(n)}`;g.length>0&&(y=e`${y} WHERE ${e.join(g,e` AND `)}`);const R=await S(a,f,y),I=[];for(const M of We(s,R)){const H=jt(ut(M[w.field]),l);H>0&&I.push({creationTime:typeof M._creationTime=="number"?M._creationTime:0,doc:M,score:H})}I.sort((M,H)=>H.score-M.score||H.creationTime-M.creationTime);const C=I.map(M=>M.doc);return typeof c=="number"?C.slice(0,Math.max(0,Math.floor(c))):C},ai=(a,f)=>{const s={eq:(n,w)=>{if(!a.definition.filterFields?.includes(n))throw new b("INTERNAL",`field "${n}" is not a filter field of search index "${a.indexName}" on table "${f}"`);return a.filters.push({field:n,value:w}),s},search:(n,w)=>{if(n!==a.definition.field)throw new b("INTERNAL",`search index "${a.indexName}" on table "${f}" indexes "${a.definition.field}", not "${n}"`);const c=a;return c.field=n,c.query=w,c.hasQuery=!0,s}};return s},oi=(a,f,s)=>[...a.partitionBy??[],...a.sortBy.map(n=>n.field),...a.where?Object.keys(a.where):[]].every(n=>f[n]===s[n]),$t=a=>a.length===1?a[0]:e`(${e.join(a,e` AND `)})`,ri=(a,f,s,n,w)=>{const c=[];for(let l=0;l<s.length+1;l+=1){const g=s.slice(0,l).map(I=>qe(a,e`${e.identifier(I)}`,n[I])),y=s[l],R=f.sortBy[l];l<s.length&&y!==void 0&&R!==void 0?g.push(e`${e.identifier(y)} ${e.raw(R.direction==="desc"?">":"<")} ${n[y]}`):g.push(e`${e.identifier(ue)} < ${w}`),c.push($t(g))}return c.length>0?e.join(c,e` OR `):void 0},si=(a,f,s)=>{if(s.length!==f.length)return;const n=[];for(const[w,c]of f.entries()){const l=[];for(let g=0;g<w;g+=1){const y=f[g];y!==void 0&&l.push(qe(a,e`${e.identifier(y.column)}`,s[g]))}l.push(e`${e.identifier(c.column)} ${e.raw(c.direction==="desc"?"<":">")} ${s[w]}`),n.push($t(l))}return e`(${e.join(n,e` OR `)})`},ci=(a,f)=>{if(a.sortBy.length===0)throw new b("INTERNAL",`rankIndex "${a.name}" requires at least one "sortBy" column for stable pagination`);const s=[{column:"__partition__",direction:"asc"}];for(const[n,w]of a.sortBy.entries())s.push({column:f[n]??G(n),direction:w.direction});return s.push({column:ue,direction:"asc"}),s},di=async(a,f,s,n,w)=>{const c=[];for(let R=0;R<w.length;R+=50)c.push(w.slice(R,R+50));const l=await Promise.all(c.map(async R=>{const I=e.join(R.map(C=>e`${C}`),e`, `);return S(a,f,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} IN (${I})`)})),g=new Map;for(const R of l)for(const I of R)g.set(I.id,I);const y=[];for(const R of w){const I=K(s,g.get(R));I&&y.push(I)}return y},li=a=>{const f=JSON.stringify(a),s=new TextEncoder().encode(f);let n="";for(const w of s)n+=String.fromCodePoint(w);return btoa(n)},Ce=500,lt=async(a,f,s,n,w)=>{let c,l=!0;for(;l;){const g=c===void 0?await S(a,f,e`SELECT * FROM ${e.identifier(n)} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Ce))}`):await S(a,f,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} > ${c} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Ce))}`);for(const y of g){const R=K(s,y);R&&w(R)}c=g.at(-1)?.id,l=g.length===Ce}},fi=(a,f)=>f.columnType(_e(a)),ui=(a,f)=>{const s=[];for(const[w,c]of Object.entries(a.shape)){if(!c._meta?.column)continue;const l=c._meta.column.notNull&&c.kind!=="optional"?" NOT NULL":"";s.push(e`${e.identifier(w)} ${e.raw(`${fi(c,f)}${l}`)}`)}const n=f.frameworkColumns().map(w=>e`${e.identifier(w.name)} ${e.raw(w.type)}`);return e.join([...n,...s],e`, `)},_i=async(a,f,s,n)=>{const w=c=>{const l=O(c),g=s.shape[c],y=g&&n.indexKeyPrefix?n.indexKeyPrefix(_e(g)):void 0;return y===void 0?l:e`${l}(${e.raw(String(y))})`};for(const c of s.indexes){const l=e.join(c.fields.map(g=>w(g)),e`, `);await ke(a,n,{columns:l,name:`${f}_${c.name}`,table:f,unique:c.unique??!1})}for(const[c,l]of Fe(s))l.unique&&await ke(a,n,{columns:w(c),name:`${f}_unique_${c}`,table:f,unique:!0})},$i=async(a,f,s)=>{for(const[n,w]of Object.entries(f.tables)){if(w.shardMode?.kind!=="global")continue;const c=ui(w,s);await v(a,s,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${c})`),await _i(a,n,w,s)}},wi=async(a,f,s)=>{const{integer:n,key:w,real:c}=s.companionTypes;for(const[l,g]of Object.entries(f.tables)){const y=g.aggregateIndexes;if(!(!y||y.length===0))for(const R of y){const I=Y(l,R.name);await v(a,s,e`CREATE TABLE IF NOT EXISTS ${e.identifier(I)} (${e.identifier("__key__")} ${e.raw(w)} PRIMARY KEY, ${e.identifier("__value__")} ${e.raw(c)}, ${e.identifier("__count__")} ${e.raw(n)} NOT NULL DEFAULT 0)`),s.name==="sqlite"&&((await S(a,s,e`PRAGMA table_info(${e.identifier(I)})`)).some(C=>C.name==="__count__")||await v(a,s,e`ALTER TABLE ${e.identifier(I)} ADD COLUMN ${e.identifier("__count__")} ${e.raw(n)} NOT NULL DEFAULT 0`))}}},Me=(a,f,s,n)=>{const w=a.name==="mysql"&&n?e`${e.identifier(f)}(191)`:e`${e.identifier(f)}`;return e`${w} ${e.raw(s)}`},hi=(a,f,s)=>{const n=[Me(a,"__partition__","ASC",!0)];for(const[w,c]of f.sortBy.entries()){const l=s.shape[c.field],g=l!==void 0&&a.indexKeyPrefix?.(_e(l))!==void 0;n.push(Me(a,G(w),c.direction==="desc"?"DESC":"ASC",g))}return n.push(Me(a,"__id__","ASC",!0)),n},Ei=(a,f,s)=>f.sortBy.map((n,w)=>{const c=s.shape[n.field],l=a.columnType(c?_e(c):void 0);return e`${e.identifier(G(w))} ${e.raw(l)}`}),mi=async(a,f,s)=>{const{key:n}=s.companionTypes;for(const[w,c]of Object.entries(f.tables)){const l=c.rankIndexes;if(!(!l||l.length===0))for(const g of l){const y=J(w,g.name),R=Ei(s,g,c),I=R.length>0?e`, ${e.join(R,e`, `)}`:e``;await v(a,s,e`CREATE TABLE IF NOT EXISTS ${e.identifier(y)} (${e.identifier("__id__")} ${e.raw(n)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(n)} NOT NULL${I})`);const C=hi(s,g,c),M=`${w}__rank_${g.name}__btree`;await ke(a,s,{columns:e.join(C,e`, `),name:M,table:y,unique:!1})}}},pi=async(a,f,s)=>{if(await De(a))for(const[n,w]of Object.entries(f.tables)){const c=w.searchIndexes;if(!(!c||c.length===0))for(const l of c){const g=xe(n,l.name);await v(a,s,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(g)} USING fts5(${e.identifier("__text__")}, ${e.identifier("__id__")} UNINDEXED)`)}}},Ne="__cdc_log",yi=async(a,f)=>{const{autoincrementPrimaryKey:s,key:n,real:w,text:c}=f.companionTypes;await v(a,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(Ne)} (${e.identifier("seq")} ${e.raw(s)}, ${e.identifier("ts")} ${e.raw(w)} NOT NULL, ${e.identifier("table")} ${e.raw(n)} NOT NULL, ${e.identifier("id")} ${e.raw(n)} NOT NULL, ${e.identifier("op")} ${e.raw(n)} NOT NULL, ${e.identifier("doc")} ${e.raw(c)})`)},gi=async(a,f,s,n,w,c,l)=>{await v(a,l,e`INSERT INTO ${e.identifier(Ne)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${f}, ${s}, ${n}, ${w}, ${c===void 0?null:JSON.stringify(c)})`)},Si=async(a,f,s)=>{const n=f.sinceSeq??0,w=Math.max(1,Math.min(f.limit??1e3,1e4)),c=(await S(a,s,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(Ne)} WHERE seq > ${n} ORDER BY seq ASC LIMIT ${e.raw(String(w))}`)).map(l=>{const{doc:g}=l,y={id:String(l.id),op:String(l.op),seq:Number(l.seq),table:String(l.table),ts:Number(l.ts)};return typeof g=="string"?{...y,doc:JSON.parse(g)}:y});return{changes:c,cursor:c.at(-1)?.seq??n}},vi=async(a,f,s)=>{await v(a,s,e`DELETE FROM ${e.identifier(Ne)} WHERE ${e.identifier("seq")} <= ${f}`)},Ii=a=>{const{crossShardCounter:f,crossShardReader:s,exec:n,maxRelationKeys:w,schema:c}=a,{dialect:l}=a,{isUniqueViolation:g}=l,y={fieldRef:O,serialize:F,...l.name==="mysql"?{likeContains:(t,i)=>e`${t} LIKE CONCAT('%', ${i}, '%') ESCAPE '\\\\'`}:{}},R=(t,i)=>qe(l.name,t,i),I=t=>{const i=e.join(t.columns.map($=>e`${e.identifier($)}`),e`, `),r=e.join(t.values.map($=>e`${$}`),e`, `),o=$=>l.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,d=$=>l.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier($)}`:e`${e.identifier($)}`,_=e.join(Object.entries(t.set(o,d)).map(([$,E])=>e`${e.identifier($)} = ${E}`),e`, `),h=l.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${_}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${_}`;return e`INSERT INTO ${e.identifier(t.table)} (${i}) VALUES (${r}) ${h}`},C=a.clock??(()=>Date.now()),M=a.idGenerator??(()=>crypto.randomUUID()),H=a.cdc??!1,be=a.auth??{identity:null,userId:null},Z=async(t,i,r,o)=>{H&&await gi(n,C(),t,i,r,o,l)},wt=a.scheduler??Ut,Re=Zt();let $e=0,Se;const U=async()=>(Se??=(async()=>{await $i(n,c,l),await wi(n,c,l),await mi(n,c,l),await pi(n,c,l),H&&await yi(n,l)})().catch(t=>{throw Se=void 0,t}),Se),ee=async(t,i)=>{await U();const r=await ei(n,l,c,t,Re);if(!(i!==void 0&&r!==i))return r},te=new Map,Ue=async(t,i)=>{const r=Y(t,i);return(await S(n,l,l.tableExists(r))).length>0},we=async(t,i)=>{const r=`${t}::${i.name}`,o=te.get(r);if(o!==void 0)return o;if(!await Ue(t,i.name))return te.set(r,!1),!1;const d=c.tables[t];if(!d)return te.set(r,!1),!1;const _=i.by??[],h=new Map;await lt(n,l,d,t,E=>{if(i.where&&!Le(E,i.where))return;const u=P(_,E);Ft(h,u,i,E)});const $=Y(t,i.name);await v(n,l,e`DELETE FROM ${e.identifier($)}`);for(const[E,u]of h)await v(n,l,e`INSERT INTO ${e.identifier($)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${E}, ${u.value}, ${u.count})`);return te.set(r,!0),!0},ht=async(t,i,r)=>{const o=ce(i.op),d=i.field??"",_=[];for(const E of i.by??[]){const u=F(r[E]??null);_.push(u===null?e`${O(E)} IS NULL`:e`${O(E)} = ${u}`)}for(const[E,u]of Object.entries(i.where??{})){const m=u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u,p=F(m);_.push(p===null?e`${O(E)} IS NULL`:e`${O(E)} = ${p}`)}const h=e`SELECT ${e.raw(o)}(${O(d)}) AS value FROM ${e.identifier(t)}`,$=await S(n,l,_.length>0?e`${h} WHERE ${e.join(_,e` AND `)}`:h);return Q($[0]?.value)},Be=async(t,i)=>{await v(n,l,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${i} AND ${e.identifier("__count__")} <= 0`)},Et=async(t,i,r,o)=>{const d=Y(t,i.name),{op:_}=i,h=i.field??"",$=r&&(!i.where||Le(r,i.where))?r:void 0,E=o&&(!i.where||Le(o,i.where))?o:void 0;if(!(!$&&!E)){if(_==="count"){const u=new Set;for(const[m,p]of[[$,-1],[E,1]]){if(!m)continue;const N=P(i.by??[],m);u.add(N),await v(n,l,I({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(T,A)=>({__count__:e`${A("__count__")} + ${T("__count__")}`,__value__:e`${A("__value__")} + ${T("__value__")}`}),table:d,values:[N,p,p]}))}for(const m of u)await Be(d,m);return}if(_==="sum"||_==="avg"){const u=new Set;for(const[m,p]of[[$,-1],[E,1]]){if(!m)continue;const N=Oe(m[h]);if(N===void 0)continue;const T=P(i.by??[],m);u.add(T),await v(n,l,I({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(A,D)=>({__count__:e`${D("__count__")} + ${A("__count__")}`,__value__:e`COALESCE(${D("__value__")}, 0) + ${A("__value__")}`}),table:d,values:[T,p*N,p]}))}for(const m of u)await Be(d,m);return}if($){const u=P(i.by??[],$),m=Oe($[h]),p=(await S(n,l,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${u}`))[0],N=Q(p?.value),T=(p?.count??0)-1;if(T<=0)await v(n,l,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${u}`);else if(p&&m!==void 0&&N!==null&&m===N){const A=await ht(t,i,$);await v(n,l,e`UPDATE ${e.identifier(d)} SET ${e.identifier("__value__")} = ${A}, ${e.identifier("__count__")} = ${T} WHERE ${e.identifier("__key__")} = ${u}`)}else await v(n,l,e`UPDATE ${e.identifier(d)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${u}`)}if(E){const u=P(i.by??[],E),m=Oe(E[h]);if(m===void 0)await v(n,l,I({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(p,N)=>({__count__:e`${N("__count__")} + 1`}),table:d,values:[u,null,1]}));else{const p=_==="min"?"MIN":"MAX";await v(n,l,I({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(N,T)=>({__count__:e`${T("__count__")} + 1`,__value__:e`${e.raw(p)}(COALESCE(${T("__value__")}, ${N("__value__")}), ${N("__value__")})`}),table:d,values:[u,m,1]}))}}}},he=async t=>{const i=c.tables[t]?.aggregateIndexes;if(!(!i||i.length===0))for(const r of i)await we(t,r)},ie=async(t,i,r)=>{const o=c.tables[t]?.aggregateIndexes;if(!(!o||o.length===0))for(const d of o){const _=`${t}::${d.name}`;(te.get(_)??await Ue(t,d.name))&&await Et(t,d,i,r)}},ne=new Map,je=async(t,i)=>{const r=J(t,i);return(await S(n,l,l.tableExists(r))).length>0},ve=async(t,i)=>{const r=`${t}::rank::${i.name}`,o=ne.get(r);if(o!==void 0)return o;if(!await je(t,i.name))return ne.set(r,!1),!1;const d=c.tables[t];if(!d)return ne.set(r,!1),!1;const _=J(t,i.name);await v(n,l,e`DELETE FROM ${e.identifier(_)}`);const h=i.sortBy.map((u,m)=>G(m)),$=e.join(["__id__","__partition__",...h].map(u=>e`${e.identifier(u)}`),e`, `),E=[];await lt(n,l,d,t,u=>{if(i.where&&!ot(u,i.where))return;const m=Te(i.partitionBy??[],u),p=i.sortBy.map(N=>F(u[N.field]??null));E.push([u._id,m,...p])});for(const u of E){const m=e.join(u.map(p=>e`${p}`),e`, `);await v(n,l,e`INSERT INTO ${e.identifier(_)} (${$}) VALUES (${m})`)}return ne.set(r,!0),!0},Ee=async t=>{const i=c.tables[t]?.rankIndexes;if(!(!i||i.length===0))for(const r of i)await ve(t,r)},z=async(t,i,r,o)=>{const d=c.tables[t],_=d?.rankIndexes;if(!_||_.length===0)return;const h=d?.softDeleteMode?.field,$=h===void 0||o===void 0?void 0:o[h],E=$!=null;for(const u of _){if(r!==void 0&&o!==void 0&&oi(u,r,o))continue;const m=`${t}::rank::${u.name}`;if(!(ne.get(m)??await je(t,u.name)))continue;const p=J(t,u.name);if(r&&await v(n,l,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier("__id__")} = ${i}`),o&&!E){if(u.where&&!ot(o,u.where))continue;const N=u.sortBy.map((L,V)=>G(V)),T=e.join(["__id__","__partition__",...N].map(L=>e`${e.identifier(L)}`),e`, `),A=Te(u.partitionBy??[],o),D=u.sortBy.map(L=>F(o[L.field]??null)),x=e.join([i,A,...D].map(L=>e`${L}`),e`, `);await v(n,l,e`INSERT INTO ${e.identifier(p)} (${T}) VALUES (${x})`)}}},ae=async(t,i,r)=>{const o=c.tables[t]?.searchIndexes;if(!(!o||o.length===0||!await De(n)))for(const d of o){const _=xe(t,d.name);await v(n,l,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier("__id__")} = ${i}`),r&&await v(n,l,e`INSERT INTO ${e.identifier(_)} (${e.identifier("__text__")}, ${e.identifier("__id__")}) VALUES (${ut(r[d.field])}, ${i})`)}},He=new Set;for(const[t,i]of Object.entries(c.tables))for(const r of Object.values(i.triggerMap??{}))He.add(`${t} ${r.timing} ${r.op}`);const B=(t,i,r)=>He.has(`${t} ${i} ${r}`);let Pe;const j=async(t,i,r)=>{if($e+=1,$e>rt)throw $e-=1,new fe(`trigger recursion exceeded ${String(rt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await Dt({ctx:Pe,event:r,op:i,schema:c,tableName:r.table,timing:t})}finally{$e-=1}},mt=async(t,i)=>{try{await v(n,l,i)}catch(r){throw g(r)?new fe(`unique constraint violation on "${t}"`,"unique"):r}},me=async(t,i)=>(await S(n,l,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${i}`))[0],pe=async(t,i,r,o)=>{if(o===void 0)return;const d=e.join(Object.keys(o).map($=>R(e`${e.identifier($)}`,o[$])),e` AND `),_=i==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${r} WHERE ${d}`:e`DELETE FROM ${e.identifier(t)} WHERE ${d}`,h=()=>{throw new fe(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(l.supportsReturning)(await S(n,l,e`${_} RETURNING ${e.identifier("id")}`)).length===0&&h();else{const $=await v(n,l,_);(l.affectedRows?l.affectedRows($??{rowsAffected:0}):0)===0&&h()}}catch($){throw g($)?new fe(`unique constraint violation on "${t}"`,"unique"):$}},pt=(t,i,r,o)=>{const d=Object.keys(t.shape);return{columns:["id","_creationTime",...d],values:[i,r,...d.map(_=>F(o[_]??null))]}},yt=async(t,i,r,o)=>{const d=xt(i,r.op,r.field,o.by,o.where);if(!d||!await we(t,d.index))return;const _=Y(t,d.index.name),h=Object.keys(d.partial);if(h.length===(d.index.by??[]).length&&h.length>0){const $=P(d.index.by??[],d.partial),E=await S(n,l,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(_)} WHERE ${e.identifier("__key__")} = ${$}`);if(E.length===0)return[];const u=E[0];return[{key:{...d.partial},value:Ae(r.op,{count:u.count,value:Q(u.value)})}]}return h.length>0?void 0:(await S(n,l,e`SELECT ${e.identifier("__key__")} AS key, ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(_)}`)).map($=>{const E=$;return{key:JSON.parse(E.key),value:Ae(r.op,{count:E.count,value:Q(E.value)})}})},Ke=t=>{const i=c.tables[t]?.shardMode?.kind;return i==="shardBy"||i==="root"},Ve=t=>{throw new b("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},Xe=(t,i)=>Ke(t)?s?s(t,i):Ve(t):W.findMany(t,i),ye=(t,i,r)=>it(t,{fetcher:Xe,maxRelationKeys:w,relationBaseWhere:r,schema:c,tableName:i}),W={async aggregate(t,i){const r=c.tables[t];if(!r)throw new b("INTERNAL",`unknown table: ${t}`);if(await U(),ce(i.op),i.op==="count")return W.count(t,{baseWhere:i.baseWhere,relationBaseWhere:i.relationBaseWhere,restrictsCounts:i.restrictsCounts,where:i.where});if(!i.field)throw new b("INTERNAL",`aggregate(${t}, { op: "${i.op}" }): "field" is required for non-count reducers`);const o=de(r.softDeleteMode,void 0),d=q(q(i.baseWhere,i.where),o),_=await ye(d,t,i.relationBaseWhere),h=_!==d;if(r.aggregateIndexes&&!i.baseWhere&&!h&&!o){const p=kt(r.aggregateIndexes,i.op,i.field,i.where);if(p&&await we(t,p.index)){const N=P(p.index.by??[],p.key),T=Y(t,p.index.name),A=(await S(n,l,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(T)} WHERE ${e.identifier("__key__")} = ${N}`))[0];return Ae(i.op,A===void 0?void 0:{count:A.count,value:Q(A.value)})}}const $=le(_,y),E=e.raw(ce(i.op)),u=e`SELECT ${E}(${O(i.field)}) AS value FROM ${e.identifier(t)}`,m=(await S(n,l,$?e`${u} WHERE ${$}`:u))[0]?.value;return m==null?null:Number(m)},async count(t,i){const r=c.tables[t];if(!r)throw new b("INTERNAL",`unknown table: ${t}`);await U();const o=Ct(i);if(o.restrictsCounts)throw new tt(t);const d=de(r.softDeleteMode,void 0),_=q(q(o.baseWhere,o.where),d),h=await ye(_,t,o.relationBaseWhere),$=h!==_;if(r.aggregateIndexes&&!o.baseWhere&&!$&&!d){const p=Mt(r.aggregateIndexes,o.where);if(p&&await we(t,p.index)){const N=P(p.index.by??[],p.key),T=Y(t,p.index.name),A=await S(n,l,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(T)} WHERE ${e.identifier("__key__")} = ${N}`);return Number(A[0]?.value??0)}}const E=le(h,y),u=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,m=await S(n,l,E?e`${u} WHERE ${E}`:u);return Number(m[0]?.count??0)},async delete(t,i,r){const o=await ee(t,i);if(!o)return;const d=c.tables[o];if(!d)return;const _=await me(o,t),h=K(d,_),$=r?.hard===!0,E=!$&&d.softDeleteMode?d.softDeleteMode.field:void 0;if(!(E&&(!h||h[E]!==null&&h[E]!==void 0))){if(B(o,"before","delete")&&await j("before","delete",{id:t,op:"delete",previous:h??void 0,table:o}),await Ot({deletedId:t,deletedReference:u=>h?.[u],findHolders:async(u,m,p)=>{if(c.tables[u]?.shardMode?.kind==="shardBy")throw new b("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${u}' is not supported — would require Query Coordinator fan-out across shards`);return(await W.findMany(u,{includeDeleted:$,where:{[m]:p}})).page},onCascade:(u,m)=>W.delete(m,void 0,r),onRestrict:u=>{throw new fe(u,"restrict")},onSetNull:(u,m,p)=>W.patch(m,{[p]:null}),schema:c,tableName:o}),await he(o),await Ee(o),E&&h){const u={...h,[E]:C()},m=e.join(Object.keys(d.shape).map(p=>e`${e.identifier(p)} = ${F(u[p]??null)}`),e`, `);await pe(o,"UPDATE",m,_),await ie(o,h,u),await z(o,t,h,void 0),await ae(o,t,u),await Z(o,t,"update",u),B(o,"after","delete")&&await j("after","delete",{id:t,op:"delete",previous:h,table:o});return}await pe(o,"DELETE",void 0,_),Re.delete(t),await ie(o,h??void 0,void 0),await z(o,t,h??void 0,void 0),await ae(o,t,void 0),await Z(o,t,"delete"),B(o,"after","delete")&&await j("after","delete",{id:t,op:"delete",previous:h??void 0,table:o})}},async findFirst(t,i={}){return(await W.findMany(t,{...i,limit:1})).page[0]??null},async findFirstOrThrow(t,i={}){const r=await W.findFirst(t,i);if(r===null)throw new Lt(`findFirstOrThrow: no "${t}" document matched`);return r},async findMany(t,i={}){const r=c.tables[t];if(!r)throw new b("INTERNAL",`unknown table: ${t}`);await U();const o=vt(i.orderBy),d=i.cursor?It(o,et(i.cursor)):void 0,_=Xe,h=async(L,V,ge,oe)=>{if(Ke(L))return f?qt(f,L,V,ge,oe):Ve(L);const X=c.tables[L];if(!X)throw new b("INTERNAL",`unknown table: ${L}`);const k=de(X.softDeleteMode,void 0),re={[V]:{in:ge}},gt=q(q(re,oe),k),Tt=await ye(gt,L,void 0),Ye=le(Tt,y),Ge=O(V);let se=e`SELECT ${Ge} AS __fk__, COUNT(*) AS count FROM ${e.identifier(L)}`;Ye&&(se=e`${se} WHERE ${Ye}`),se=e`${se} GROUP BY ${Ge}`;const Nt=await S(n,l,se),ze=new Map;for(const Je of Nt)ze.set(Je.__fk__,Number(Je.count??0));return ze};let $=q(i.baseWhere,i.where);$=q($,de(r.softDeleteMode,i.includeDeleted)),$=await it($,{fetcher:_,maxRelationKeys:w,relationBaseWhere:i.relationBaseWhere,schema:c,tableName:t}),d&&($=$?{AND:[$,d]}:d);const E=le($,y),u=Yt(o);let m=e`SELECT * FROM ${e.identifier(t)}`;E&&(m=e`${m} WHERE ${E}`),m=e`${m} ORDER BY ${u}`;const p=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0;p!==void 0&&(m=e`${m} LIMIT ${e.raw(String(p+1))}`);const N=await S(n,l,m),T=We(r,N);if(p===void 0)return i.with&&await nt({fetcher:_,groupedCounter:h,parents:T,schema:c,tableName:t,with:i.with}),{continueCursor:null,isDone:!0,page:at(T,i.select,i.with)};const A=T.length>p,D=A?T.slice(0,p):T,x=D.at(-1);return i.with&&await nt({fetcher:_,groupedCounter:h,parents:D,schema:c,tableName:t,with:i.with}),{continueCursor:A&&x?At(x,o):null,isDone:!A,page:at(D,i.select,i.with)}},async get(t,i){const r=await ee(t,i);if(!r)return null;const o=c.tables[r];if(!o)return null;const d=await S(n,l,e`SELECT * FROM ${e.identifier(r)} WHERE ${e.identifier("id")} = ${t}`);return K(o,d[0])},async groupBy(t,i){const r=c.tables[t];if(!r)throw new b("INTERNAL",`unknown table: ${t}`);await U();const o=i.agg??{op:"count"};if(ce(o.op),o.op!=="count"&&!o.field)throw new b("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const d=de(r.softDeleteMode,void 0),_=q(q(i.baseWhere,i.where),d),h=await ye(_,t,i.relationBaseWhere),$=h!==_;if(r.aggregateIndexes&&!i.baseWhere&&!$&&!d){const T=await yt(t,r.aggregateIndexes,o,i);if(T!==void 0)return T}const E=le(h,y),u=i.by.map(T=>e`${O(T)} AS ${e.identifier(T)}`);if(o.op==="count")u.push(e`COUNT(*) AS value`);else{if(!o.field)throw new b("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);u.push(e`${e.raw(ce(o.op))}(${O(o.field)}) AS value`)}const m=e.join(i.by.map(T=>O(T)),e`, `);let p=e`SELECT ${e.join(u,e`, `)} FROM ${e.identifier(t)}`;E&&(p=e`${p} WHERE ${E}`),p=e`${p} GROUP BY ${m}`;const N=await S(n,l,p);return ti(i.by,N)},async insert(t,i,r){const o=c.tables[t];if(!o)throw new b("INTERNAL",`unknown table: ${t}`);await U();const d=Jt(o,i,be);Ie(o,d);let _,h=!0;r?.clientId!==void 0?(St(r.clientId),_=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?_=d._id:(_=M(),h=!1);const $=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:C(),E={...d,_creationTime:$,_id:_};B(t,"before","insert")&&await j("before","insert",{doc:{...E},id:_,op:"insert",table:t}),await he(t),await Ee(t);const{columns:u,values:m}=pt(o,_,$,d),p=e.join(u.map(T=>e`${e.identifier(T)}`),e`, `),N=e.join(m.map(T=>e`${T}`),e`, `);return await mt(t,e`INSERT INTO ${e.identifier(t)} (${p}) VALUES (${N})`),h&&Re.set(_,t),await ie(t,void 0,E),await z(t,_,void 0,E),await ae(t,_,E),await Z(t,_,"insert",E),B(t,"after","insert")&&await j("after","insert",{doc:E,id:_,op:"insert",table:t}),_},normalizeId(t,i){return Rt(c,t,i)},async patch(t,i,r){const o=await ee(t,r);if(!o)throw new b("INTERNAL",`document not found: ${t}`);const d=c.tables[o];if(!d)throw new b("INTERNAL",`document not found: ${t}`);const _=await me(o,t),h=K(d,_);if(!h)throw new b("INTERNAL",`document not found: ${t}`);const $={...h,...i,_id:t};dt(d,i,$,be),Ie(d,$),B(o,"before","update")&&await j("before","update",{doc:{...$},id:t,op:"update",previous:h,table:o}),await he(o),await Ee(o);const E=Object.keys(d.shape),u=e.join(E.map(m=>e`${e.identifier(m)} = ${F($[m]??null)}`),e`, `);await pe(o,"UPDATE",u,_),await ie(o,h,$),await z(o,t,h,$),await ae(o,t,$),await Z(o,t,"update",$),B(o,"after","update")&&await j("after","update",{doc:$,id:t,op:"update",previous:h,table:o})},async restore(t,i){const r=await ee(t,i);if(!r)throw new b("INTERNAL",`document not found: ${t}`);const o=c.tables[r],d=o?.softDeleteMode?.field;if(!o||!d)throw new b("INTERNAL",`ctx.db.restore: table "${r}" is not a .softDelete() table`);const _=await me(r,t),h=_?.[d]!==null&&_?.[d]!==void 0;if(await W.patch(t,{[d]:null},i),h){const $=K(o,_);$!==null&&await z(r,t,void 0,{...$,[d]:null})}},query(t){const i=c.tables[t];if(!i)throw new b("INTERNAL",`unknown table: ${t}`);const r="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=async(_,h)=>(await U(),await De(n)?ii(n,l,i,t,_,h):ni(n,l,i,t,_,h)),d=_=>{const h={async collect(){if(!_)throw new b("INTERNAL",r);return o(_,void 0)},filter(){throw new b("INTERNAL",r)},async first(){if(!_)throw new b("INTERNAL",r);return(await o(_,1))[0]??null},order(){return h},async paginate(){throw _?new b("INTERNAL","pagination is not supported on search queries; use .take(n) or .collect()"):new b("INTERNAL",r)},async take($){if(!_)throw new b("INTERNAL",r);return o(_,$)},async unique(){if(!_)throw new b("INTERNAL",r);const $=await o(_,2);if($.length>1)throw new Wt(`unique() on table "${t}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex(){throw new b("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new b("INTERNAL",r)},withSearchIndex($,E){const u=(i.searchIndexes??[]).find(p=>p.name===$);if(!u)throw new b("INTERNAL",`unknown search index "${$}" on table "${t}"`);const m={definition:u,field:u.field,filters:[],hasQuery:!1,indexName:$,query:""};if(E(ai(m,t)),!m.hasQuery)throw new b("INTERNAL",`search index "${$}" on table "${t}" requires a .search(field, query) call`);return d(m)}};return h};return d(void 0)},async rank(t,i,r){const o=c.tables[t];if(!o)throw new b("INTERNAL",`unknown table: ${t}`);const d=o.rankIndexes?.find(x=>x.name===i);if(!d)throw new b("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(r.restrictsCounts)throw new tt(t);if(await U(),!await ve(t,d))return null;const _=typeof r.row=="string"?r.row:r.row._id;if(!_)return null;const h=J(t,d.name),$=d.sortBy.map((x,L)=>G(L)),E=e.join([e`${e.identifier("__partition__")}`,...$.map(x=>e`${e.identifier(x)}`)],e`, `),u=(await S(n,l,e`SELECT ${E} FROM ${e.identifier(h)} WHERE ${e.identifier("__id__")} = ${_}`))[0];if(!u)return null;const m=u.__partition__,p=q(r.baseWhere,r.where);Qe(p,c,t,"rank");const N=Ze(d,p);if(N&&Te(d.partitionBy??[],N)!==m)return null;const T=ri(l.name,d,$,u,_),A=await S(n,l,e`SELECT COUNT(*) AS c FROM ${e.identifier(h)} WHERE ${e.identifier("__partition__")} = ${m}${T?e` AND (${T})`:e``}`),D=await S(n,l,e`SELECT COUNT(*) AS c FROM ${e.identifier(h)} WHERE ${e.identifier("__partition__")} = ${m}`);return{position:Number(A[0]?.c??0)+1,total:Number(D[0]?.c??0)}},async rankPage(t,i,r={}){Qe(q(r.baseWhere,r.where),c,t,"rankPage");const o=c.tables[t];if(!o)throw new b("INTERNAL",`unknown table: ${t}`);const d=o.rankIndexes?.find(k=>k.name===i);if(!d)throw new b("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(await U(),!await ve(t,d))return{continueCursor:null,isDone:!0,page:[]};const _=J(t,d.name),h=d.sortBy.map((k,re)=>G(re)),$=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),E=q(r.baseWhere,r.where),u=Ze(d,E),m=ci(d,h),p=e.join(m.map(k=>e`${e.identifier(k.column)} ${e.raw(k.direction==="desc"?"DESC":"ASC")}`),e`, `),N=[];if(u&&N.push(e`${e.identifier("__partition__")} = ${Te(d.partitionBy??[],u)}`),r.cursor){const k=si(l.name,m,et(r.cursor));k!==void 0&&N.push(k)}const T=e.join([e`${e.identifier(ue)}`,e`${e.identifier("__partition__")}`,...h.map(k=>e`${e.identifier(k)}`)],e`, `);let A=e`SELECT ${T} FROM ${e.identifier(_)}`;N.length>0&&(A=e`${A} WHERE ${e.join(N,e` AND `)}`),A=e`${A} ORDER BY ${p} LIMIT ${e.raw(String($+1))}`;const D=await S(n,l,A),x=D.length>$,L=x?D.slice(0,$):D,V=L.map(k=>k[ue]),ge=await di(n,l,o,t,V);let oe=null;const X=L.at(-1);if(x&&X!==void 0){const k=[X.__partition__,...h.map(re=>X[re]),X[ue]];oe=li(k)}return{continueCursor:oe,isDone:!x,page:ge}},async replace(t,i,r,o){const d=await ee(t,r);if(!d)throw new b("INTERNAL",`document not found: ${t}`);const _=c.tables[d];if(!_)throw new b("INTERNAL",`document not found: ${t}`);const h=await me(d,t);if(h===void 0)throw new b("INTERNAL",`document not found: ${t}`);const $=bt(c,d,"update")||(_.aggregateIndexes??[]).length>0||(_.rankIndexes??[]).length>0?K(_,h)??void 0:void 0,E=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:C(),u={...i,_creationTime:E,_id:t};dt(_,i,u,be),Ie(_,u),B(d,"before","update")&&await j("before","update",{doc:{...u},id:t,op:"update",previous:$,table:d}),await he(d),await Ee(d);const m=Object.keys(_.shape),p=e.join([e`${e.identifier("_creationTime")} = ${E}`,...m.map(N=>e`${e.identifier(N)} = ${F(u[N]??null)}`)],e`, `);await pe(d,"UPDATE",p,h),await ie(d,$,u),await z(d,t,$,u),await ae(d,t,u),await Z(d,t,"update",u),B(d,"after","update")&&await j("after","update",{doc:u,id:t,op:"update",previous:$,table:d})}};return Pe={db:W,scheduler:wt},W};export{Ii as createSqlCtxDb,zt as decodeGlobalRow,Si as readSqlCdcChanges,wi as runSqlAggregateMigrations,yi as runSqlCdcMigration,$i as runSqlGlobalTableMigrations,mi as runSqlRankMigrations,pi as runSqlSearchMigrations,vi as trimSqlCdcChanges};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=t=>typeof t=="boolean"?t?1:0:t===null||typeof t=="string"||typeof t=="number"?t:typeof t=="bigint"?t.toString():t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):JSON.stringify(t),e=t=>{try{return JSON.parse(t)}catch{return t}},i=t=>{if(typeof t!="string")return t;try{return BigInt(t)}catch{return t}},o=t=>{if(t.kind!=="optional")return t.kind;const r=t._meta?.inner;return r?o(r):t.kind},s=(t,r)=>{if(t===null)return t;switch(r){case"any":case"union":return typeof t=="string"&&(t.startsWith("{")||t.startsWith("["))?e(t):t;case"array":case"object":case"record":return typeof t=="string"?e(t):t;case"bigint":return i(t);case"boolean":return t===0||t===1?t===1:t;default:return t}};export{i as decodeBigint,o as effectiveColumnKind,s as sqliteDecode,a as sqliteEncode,e as tryJsonParse};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/sql-store",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.43",
|
|
4
4
|
"description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/do": "1.0.0-alpha.
|
|
53
|
+
"@lunora/do": "1.0.0-alpha.46",
|
|
54
54
|
"@lunora/errors": "1.0.0-alpha.8",
|
|
55
55
|
"drizzle-orm": "^0.45.2"
|
|
56
56
|
},
|