@lunora/sql-store 1.0.0-alpha.220 → 1.0.0-alpha.221
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/index.d.mts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-CH0YDOni.mjs → SEARCH_STATE_TABLE-CtoIJ1PM.mjs} +1 -1
- package/dist/packem_shared/backfillSqlSearchIndexes-LRAu-CxC.mjs +1 -0
- package/dist/packem_shared/{createSqlCtxDb-B2y2spnC.mjs → createSqlCtxDb-BIehyqW5.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-DhPvgSgA.mjs → ctx-db-search-D_0SkyeY.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-CaX6vwUz.mjs → ctx-db-search-state-C4l9QBq-.mjs} +1 -1
- package/dist/packem_shared/decodeGlobalRow-DC2qlCZl.mjs +1 -0
- package/dist/packem_shared/exportSqlGlobalRows-Bo4Ytr_-.mjs +1 -0
- package/dist/packem_shared/facetSqlGlobalColumn-CzVBGmYR.mjs +1 -0
- package/dist/packem_shared/{runSqlAggregateMigrations-DY65VtGl.mjs → runSqlAggregateMigrations-Bje8kPUQ.mjs} +1 -1
- package/dist/packem_shared/{runSqlGlobalTableMigrations-CIbF4adm.mjs → runSqlGlobalTableMigrations-C24sSQdc.mjs} +1 -1
- package/dist/packem_shared/sql-exec-CkHeSf_v.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/backfillSqlSearchIndexes-BKT_YmAk.mjs +0 -1
- package/dist/packem_shared/decodeGlobalRow-Bc_0zTWY.mjs +0 -1
- package/dist/packem_shared/exportSqlGlobalRows-6sS_vU9b.mjs +0 -1
- package/dist/packem_shared/facetSqlGlobalColumn-BEE13w0Y.mjs +0 -1
- package/dist/packem_shared/sql-exec-snQLgtvn.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -115,9 +115,13 @@ interface ImportGlobalArgs {
|
|
|
115
115
|
/**
|
|
116
116
|
* Import rows into `.global()` tables via the schema-aware writer. The
|
|
117
117
|
* writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
|
|
118
|
-
* absent); we
|
|
118
|
+
* absent); we probe the rows' `_id`s first so a collision is reported as a
|
|
119
119
|
* conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
|
|
120
120
|
* `errors`; the rest land.
|
|
121
|
+
*
|
|
122
|
+
* With an `exec` handle the probe is batched ({@link probeIdOwners}) once for
|
|
123
|
+
* the whole call, not per row; a live write between that probe and a row's
|
|
124
|
+
* insert can still create a cross-table duplicate.
|
|
121
125
|
*/
|
|
122
126
|
declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
|
|
123
127
|
interface SqlCtxDbOptions {
|
package/dist/index.d.ts
CHANGED
|
@@ -115,9 +115,13 @@ interface ImportGlobalArgs {
|
|
|
115
115
|
/**
|
|
116
116
|
* Import rows into `.global()` tables via the schema-aware writer. The
|
|
117
117
|
* writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
|
|
118
|
-
* absent); we
|
|
118
|
+
* absent); we probe the rows' `_id`s first so a collision is reported as a
|
|
119
119
|
* conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
|
|
120
120
|
* `errors`; the rest land.
|
|
121
|
+
*
|
|
122
|
+
* With an `exec` handle the probe is batched ({@link probeIdOwners}) once for
|
|
123
|
+
* the whole call, not per row; a live write between that probe and a row's
|
|
124
|
+
* insert can still create a cross-table duplicate.
|
|
121
125
|
*/
|
|
122
126
|
declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
|
|
123
127
|
interface SqlCtxDbOptions {
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportSqlGlobalRows as l,importSqlGlobalRows as o,selectGlobalTables as r}from"./packem_shared/exportSqlGlobalRows-
|
|
1
|
+
import{exportSqlGlobalRows as l,importSqlGlobalRows as o,selectGlobalTables as r}from"./packem_shared/exportSqlGlobalRows-Bo4Ytr_-.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as n,readSqlCdcFloor as i,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-BIehyqW5.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-C24sSQdc.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-Bje8kPUQ.mjs";import{b as x,r as C}from"./packem_shared/ctx-db-search-D_0SkyeY.mjs";import{S as T,m as u}from"./packem_shared/ctx-db-search-state-C4l9QBq-.mjs";import{facetSqlGlobalColumn as h,listSqlGlobalTables as M,readSqlGlobalTablePage as w}from"./packem_shared/facetSqlGlobalColumn-CzVBGmYR.mjs";import{d as E,e as k,s as B,a as D,t as P}from"./packem_shared/value-codec-C52YW-Do.mjs";import{d as v}from"./packem_shared/sql-exec-CkHeSf_v.mjs";export{T as SEARCH_STATE_TABLE,x as backfillSqlSearchIndexes,s as createSqlCtxDb,E as decodeBigint,v as decodeGlobalRow,k as effectiveColumnKind,l as exportSqlGlobalRows,h as facetSqlGlobalColumn,o as importSqlGlobalRows,M as listSqlGlobalTables,u as migrateSearchState,S as readSqlCdcChangedTables,n as readSqlCdcChanges,i as readSqlCdcFloor,w as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,C as runSqlSearchMigrations,r as selectGlobalTables,B as sqliteDecode,D as sqliteEncode,q as sweepSqlCdcRetention,P as tryJsonParse};
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-CH0YDOni.mjs → SEARCH_STATE_TABLE-CtoIJ1PM.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-
|
|
1
|
+
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-C4l9QBq-.mjs";import"./sql-exec-CkHeSf_v.mjs";export{t as SEARCH_STATE_TABLE,S as clearSearchBackfillState,c as migrateSearchState,l as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ctx-db-search-state-C4l9QBq-.mjs";import{b as S,c as s,a as i,r as l}from"./ctx-db-search-D_0SkyeY.mjs";import"./sql-exec-CkHeSf_v.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{m as Rn,q as Sn}from"./ctx-db-search-state-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{m as Rn,q as Sn}from"./ctx-db-search-state-C4l9QBq-.mjs";import{c as gn,r as mn,A as Tn,C as vn,R as In,u as An,a as Cn,T as Ln,x as bn,d as Nn}from"./ctx-db-search-D_0SkyeY.mjs";import{throwingScheduler as Mn,describeRelationWrites as On,CDC_LOG_TABLE as D,cdcForkedError as qn,cursorBelowRetainedFloor as kn,cdcTrimmedError as Dn,serverInList as Bn,assertNoExplicitUndefined as Ke,hasTrigger as Wn,runRowValidators as Ge,assertFlatPredicate as Et,mergeWhere as F,rankTableName as _e,sortColumnName as Re,resolveRankPartition as pt,encodePartitionKey as Me,resolveRankSeekTuple as Fn,RANK_TIEBREAK as Se,CountRlsUnsupportedError as yt,compileWhereSql as z,ConflictError as ae,patchDependsOnRow as Un,normalizeIdStructurally as xn,applyInsertDefaults as Pn,assertValidClientId as Hn,assertStorableRowId as jn,aggregateSqlFunction as Ee,softDeleteScope as Oe,resolveWith as Rt,relationHooks as St,applySelect as gt,encodeCursor as Kn,NotFoundError as Gn,applyOnDelete as Vn,normalizeCountArgument as Yn,selectIndexForCount as Xn,encodeAggregateKey as J,aggregateTableName as ie,selectIndexForAggregate as Qn,readAggregateValue as Ve,runTriggers as zn,nullsOrderSuffix as mt,nullsFirstOf as Tt,rankPivotConditionSql as Ht,CURSOR_PREFIX as Jn,resolvePatch as Zn,stripReservedPatchFields as ei,assertPatchAllowed as ti,resolveRelationPredicates as ni,selectIndexForGroupBy as ii,composeReadPredicate as oi,fanOutScalarCounts as ri,whereOfFilter as si,isPushableWhere as ai,matchesRankStaticWhere as vt,tiebreakDirectionFor as ci,matchesStaticWhere as Ye,coerceAggregateNumber as Xe,foldAggregateTally as It,CDC_LOG_TABLE_SEQ_INDEX as di,NotUniqueError as li,WORKERD_SQLITE_LIMITS as ui}from"@lunora/shard-engine";import{decodeWire as jt,needsWireEncoding as Kt,encodeWire as Gt}from"@lunora/wire";import{sql as e,SQL as fi}from"drizzle-orm";import{p as At,h as Ct,q as I,b as x,c as Vt,i as wi,j as $i,k as hi,l as X,s as oe,O as pe,e as U,m as Lt,t as _i,a as Ei,n as bt,o as Be,u as ot,v as Nt,w as pi,x as Qe,y as Mt,B as ze,z as Ot,g as qt}from"./sql-exec-CkHeSf_v.mjs";import{d as Ro}from"./sql-exec-CkHeSf_v.mjs";import{runSqlGlobalTableMigrations as yi}from"./runSqlGlobalTableMigrations-C24sSQdc.mjs";import{runSqlAggregateMigrations as Ri,runSqlRankMigrations as Si}from"./runSqlAggregateMigrations-Bje8kPUQ.mjs";import{s as Yt,e as Xt}from"./value-codec-C52YW-Do.mjs";const gi=(r,a)=>{if(r.size<a)return;const u=r.keys().next().value;u!==void 0&&r.delete(u)},kt=50,mi=(r,a={})=>{const u=a.maxBatch??kt,c=Number.isInteger(u)&&u>0?u:kt,R=new Map;let f=!1;const d=async(T,A)=>{const v=[...A.keys()];for(let L=0;L<v.length;L+=c){const b=v.slice(L,L+c);try{const q=await r(T,b);for(const K of b){const Q=q.get(K);for(const Z of A.get(K)??[])Z.resolve(Q)}}catch(q){for(const K of b)for(const Q of A.get(K)??[])Q.reject(q)}}},O=()=>{f=!1;const T=[...R.entries()];R.clear();for(const[A,v]of T)d(A,v).catch(()=>{})};return{async load(T,A){return new Promise((v,L)=>{let b=R.get(T);b||(b=new Map,R.set(T,b));const q=b.get(A);q?q.push({reject:L,resolve:v}):b.set(A,[{reject:L,resolve:v}]),f||(f=!0,queueMicrotask(O))})}}},Ti=new Set(["_id","id"]),vi=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},Qt=(r,a)=>{const u=a.direction==="desc"?"DESC":"ASC",c=a.nullable===!0,R=f=>e`${Be(r,a.field)} ${e.raw(`${u}${f}`)}`;switch(r.name){case"mysql":{const f=R("");return!c||a.nulls===void 0?[f]:[e`(${Be(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,f]}case"postgres":return[R(c?mt(Tt(a)):"")];case"sqlite":return[R(c&&a.nulls!==void 0?mt(Tt(a)):"")];default:return vi(r.name)}},Ii=(r,a)=>{const u=r.flatMap(c=>Qt(a,c));if(!r.some(c=>Ti.has(c.field))){const c=ci(r);u.push(e`${U("id")} ${e.raw(c==="desc"?"DESC":"ASC")}`)}return e.join(u,e`, `)},Dt=50,Ai=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},Je=(r,a,u,c)=>{for(const[R,f]of _i(r)){if(f.serverDefault){R in a&&(u[R]=f.serverDefault({auth:c}));continue}f.onUpdateFn&&!(R in a)&&(u[R]=f.onUpdateFn())}},Ci=128,Li=()=>{const r=new Map;return{delete:a=>{r.delete(a)},get:a=>{const u=r.get(a);if(u!==void 0)return r.delete(a),r.set(a,u),u},set:(a,u)=>{r.has(a)?r.delete(a):gi(r,Ci),r.set(a,u)}}},zt=r=>r.shardMode===void 0||r.shardMode.kind==="global",bi=async(r,a,u,c,R)=>{const f=R.get(c);if(f!==void 0)return f;const d=Object.entries(u.tables).filter(([,T])=>zt(T)).map(([T])=>T),O=await Promise.all(d.map(async T=>({found:(await I(r,a,e`SELECT 1 FROM ${e.identifier(T)} WHERE ${e.identifier("id")} = ${c} LIMIT 1`)).length>0,tableName:T})));for(const T of O)if(T.found)return R.set(c,T.tableName),T.tableName},ce=r=>r==null?null:Number(r),Ni=(r,a,u)=>u.map(c=>{const R={};for(const f of a){const d=r.shape[f];R[f]=Yt(c[f]??null,d&&Xt(d))}return{key:R,value:ce(c.value)}}),Mi=(r,a,u)=>[...r.partitionBy??[],...r.sortBy.map(R=>R.field),...r.where?Object.keys(r.where):[]].every(R=>Mt(a,R)===Mt(u,R)),Jt=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,re=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),de=r=>e.join(r.map(a=>e`${a}`),e`, `),Ze=(r,a)=>{if(r==="postgres"){for(const[u,c]of Object.entries(a))if(typeof c=="string"&&c.includes("\0"))throw new g("BAD_REQUEST",`"${u}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,Oi=(r,a,u,c,R)=>{const f=[];for(let d=0;d<u.length+1;d+=1){const O=u[d],T=a.sortBy[d],A=d<u.length&&O!==void 0&&T!==void 0,v=T?.direction==="desc"?"desc":"asc",L=A?Ht(O,We(c[O]),v,!1):e`${e.identifier(Se)} < ${R}`;if(L===void 0)continue;const b=u.slice(0,d).map(q=>ot(r,e`${e.identifier(q)}`,We(c[q])));b.push(L),f.push(Jt(b))}return f.length>0?e.join(f,e` OR `):e`1 = 0`},qi=(r,a,u)=>{if(u.length!==a.length)return;const c=[];for(const[R,f]of a.entries()){const d=Ht(f.column,We(u[R]),f.direction,!0);if(d===void 0)continue;const O=[];for(let T=0;T<R;T+=1){const A=a[T];A!==void 0&&O.push(ot(r,e`${e.identifier(A.column)}`,We(u[T])))}O.push(d),c.push(Jt(O))}return c.length===0?e`(1 = 0)`:e`(${e.join(c,e` OR `)})`},ki=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const u=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[c,R]of r.sortBy.entries())u.push({column:a[c]??Re(c),direction:R.direction,nullable:!0});return u.push({column:Se,direction:"asc",nullable:!1}),u},Di=async(r,a,u,c,R)=>{const d=[];for(let v=0;v<R.length;v+=50)d.push(R.slice(v,v+50));const O=await Promise.all(d.map(async v=>I(r,a,e`SELECT * FROM ${e.identifier(c)} WHERE ${e.identifier("id")} IN (${de(v)})`))),T=new Map;for(const v of O)for(const L of v)T.set(L.id,L);const A=[];for(const v of R){const L=X(u,T.get(v));L&&A.push(L)}return A},Bi=r=>{const a=r.map(f=>Yt(f,"bytes")),u=JSON.stringify(Kt(a)?Gt(a):a),c=new TextEncoder().encode(u);let R="";for(const f of c)R+=String.fromCodePoint(f);return Jn+btoa(R)},Zt=r=>{if(r===void 0)return!1;const a=Xt(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},nt=(r,a,u)=>{if(Zt(r.shape[a]))throw new g("BAD_REQUEST",`${u}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Wi=(r,a,u,c)=>{for(const R of u)nt(r,R,`groupBy(${a}, { by: [..."${R}"] })`);c.field!==void 0&&nt(r,c.field,`groupBy(${a}, { agg: { op: "${c.op}", field: "${c.field}" } })`)},it="__cdc_sweep",qe="__cdc_log_ts",en="global",Fi=6e4,Ui=1e4,xi=3e4;let Bt=0;const Pi=async(r,a)=>{const{autoincrementPrimaryKey:u,key:c,real:R,text:f}=a.companionTypes;await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(D)} (${e.identifier("seq")} ${e.raw(u)}, ${e.identifier("ts")} ${e.raw(R)} NOT NULL, ${e.identifier("table")} ${e.raw(c)} NOT NULL, ${e.identifier("id")} ${e.raw(c)} NOT NULL, ${e.identifier("op")} ${e.raw(c)} NOT NULL, ${e.identifier("doc")} ${e.raw(f)})`);const d=a.indexKeyPrefix?.("string");await Vt(r,a,{columns:e`${d===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(d))})`}, ${e.identifier("seq")}`,name:di,table:D,unique:!1}),await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(it)} (${e.identifier("id")} ${e.raw(c)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(R)} NOT NULL)`),await x(r,a,e`INSERT INTO ${e.identifier(it)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${en}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Hi=async(r,a,u)=>{const c=e`UPDATE ${e.identifier(it)} SET ${e.identifier("lease_until")} = ${u+Fi} WHERE ${e.identifier("id")} = ${en} AND ${e.identifier("lease_until")} <= ${u}`;if(a.supportsReturning)return(await I(r,a,e`${c} RETURNING ${e.identifier("id")}`)).length>0;const R=await x(r,a,c);return(a.affectedRows?a.affectedRows(R??{rowsAffected:0}):0)>0},ji=async(r,a,u,c)=>{if(!await Hi(r,a,c))return;const R=c-u;let f=!0;try{const d=await wi(r,a,D,qe);d!=="valid"&&(d==="invalid"&&await $i(r,a,D,qe),await Vt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:qe,table:D,unique:!1}))}catch(d){f=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${qe}"; sweeping without it.`,d)}f&&(await I(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(D)} WHERE ${e.identifier("ts")} <= ${R} LIMIT 1`)).length===0||await x(r,a,e`
|
|
2
2
|
DELETE FROM ${e.identifier(D)} WHERE ${e.identifier("seq")} IN (
|
|
3
3
|
SELECT ${e.identifier("seq")} FROM (
|
|
4
4
|
SELECT ${e.identifier("seq")} FROM ${e.identifier(D)} WHERE +${e.identifier("ts")} <= ${R} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Ui))}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{q,c as vt,m as Dt,r as F,a as qt,l as lt,w as D,b as Ft}from"./ctx-db-search-state-CaX6vwUz.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ut,ftsWriteDocument as mt,ftsPurgeDocument as pt,ftsCompanionDdl as kt,unionAll as Ht,ftsRowidMapName as Pt}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{q as p,O as Bt,u as jt,l as Q,a as A,i as C,c as V,j as L,b as T,m as ht,e as rt,x as Wt,r as xt,z as Kt}from"./sql-exec-snQLgtvn.mjs";const Gt=n=>{const t=atob(n),e=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(e)},Yt=()=>new h("BAD_REQUEST","invalid cursor"),st=16,ot=8,y=1024,b=(n,t)=>t.query(n),Qt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",r=(e.codePointAt(0)??0)+1;if(r>=55296&&r<=57343||r>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(r)}},Cn=(n,t,e)=>{const r={eq:(s,o)=>{if(!n.definition.filterFields?.includes(s))throw new h("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=ot)throw new h("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(ot)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:o}),r},search:(s,o)=>{const a=n;if(s!==a.definition.field)throw new h("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${s}"`);const f=b(o,e).length;if(f>st)throw new h("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=s,a.query=o,a.hasQuery=!0,r}};return r},Ln=n=>{if(n.length>y)throw new h("BAD_REQUEST",`more than ${String(y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Mn=n=>Math.min(n.offset+n.numItems+1,y),Vt=n=>btoa(`search:${String(n)}`),Xt=n=>{let t;try{t=Gt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},vn=n=>{if(typeof n.endCursor=="string")throw new h("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new h("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Xt(n.cursor):0;if(e===void 0)throw Yt();if(e+t>=y)throw new h("BAD_REQUEST",`search pagination reaches the ${String(y)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,y-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},Dn=(n,t)=>{const e=t.offset+t.numItems,r=t.numItems>0&&n.length>e;return{continueCursor:r?Vt(e):null,isDone:!r,page:n.slice(t.offset,e)}},qn=n=>{if(n===void 0)return y+1;if(!Number.isFinite(n))return y;const t=Math.max(0,Math.floor(n));if(t>y)throw new h("BAD_REQUEST",`search returns at most ${String(y)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},Jt=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const r of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[r]}return e},U=(n,t)=>`${n}__fts_${t}`,S="__id__",g="__token__",O="__n__",zt=1e3,Zt=(n,t)=>t.document(n),W=(n,t)=>Jt(n,t),tn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",nn=(n,t,e)=>n!==void 0&&t!==void 0&&W(n,e.field)===W(t,e.field),gt=(n,t)=>Zt(tn(W(n,t.field)),q(t.language)).slice(0,zt),X=(n,t)=>gt(n,t).join(" "),Tt=(n,t)=>{const e=new Map;for(const r of gt(n,t))e.set(r,(e.get(r)??0)+1);return e},yt=[Bt,"_creationTime"],at=50,$=(n,t)=>i`${i.identifier(n)}.${i.identifier(t)}`,M=(n,t,e)=>i`DELETE FROM ${i.identifier(n)} WHERE ${$(n,S)} = ${t}${e===void 0?i``:i` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const r=yt.map(s=>i` AND ${jt(n.name,$(e,s),t[s]??null)}`);return i`SELECT 1 FROM ${i.identifier(e)} WHERE ${$(e,"id")} = ${t.id}${i.join(r)}${n.name==="postgres"?i` FOR SHARE`:i``}`},v=(n,t)=>i`EXISTS (${Rt(n,t)})`,k=(n,t)=>i`NOT EXISTS (SELECT 1 FROM ${i.identifier(n)} WHERE ${$(n,"id")} = ${t})`,_t=(n,t,e,r)=>r===void 0?k(t,e):v(n,{row:r,table:t}),J=async(n,t,e,r)=>{const s=new Map;for(let o=0;o<r.length;o+=at){const a=r.slice(o,o+at),f=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${$(e,"id")} IN (${i.join(a.map(u=>i`${u}`),i`, `)})`);for(const u of f)s.set(String(u.id),u)}return s},x=(n,t,e)=>n.name==="mysql"?i`${i.identifier(t)}(${i.raw(String(e))})`:n.textPatternOperatorClass===void 0?i`${i.identifier(t)}`:i`${i.identifier(t)} ${i.raw(n.textPatternOperatorClass)}`,z=512,Z=(n,t)=>({columns:i`${x(n,g,256)}, ${x(n,S,z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),B=n=>i`${n} COLLATE utf8mb4_0900_bin`,j=(n,t)=>{const e=JSON.stringify(t.map(([r,s])=>({o:s,t:r})));switch(n.name){case"mysql":return i`JSON_TABLE(${e}, '$[*]' COLUMNS (${i.identifier("t")} VARCHAR(256) PATH '$.t', ${i.identifier("o")} INT PATH '$.o')) AS ${i.identifier("j")}`;case"postgres":return i`json_to_recordset(${e}::text::json) AS ${i.identifier("j")}(${i.identifier("t")} text, ${i.identifier("o")} integer)`;default:return i`(SELECT json_extract(${$("e","value")}, '$.t') AS ${i.identifier("t")}, json_extract(${$("e","value")}, '$.o') AS ${i.identifier("o")} FROM json_each(${e}) AS ${i.identifier("e")}) AS ${i.identifier("j")}`}},Nt=(n,t,e,r,s)=>{const o=i.join([g,S,O].map(f=>i.identifier(f)),i`, `),a=f=>i`INSERT INTO ${i.identifier(t)} (${o}) SELECT ${$("j","t")}, ${e}, ${$("j","o")} FROM ${j(n,r)} WHERE ${f}`;switch(n.name){case"mysql":{const f=v(n,s),u=$(t,g),c=i.identifier("held");return[i`${a(i`${f} AND NOT EXISTS (SELECT 1 FROM ${i.identifier(t)} AS ${c} WHERE ${$("held",S)} = ${e} AND ${$("held",g)} = ${B($("j","t"))})`)} ON DUPLICATE KEY UPDATE ${$(t,O)} = ${$(t,O)}`,i`UPDATE ${i.identifier(t)} JOIN ${j(n,r)} ON ${u} = ${B($("j","t"))} SET ${$(t,O)} = ${$("j","o")} WHERE ${$(t,S)} = ${e} AND ${f}`,i`DELETE FROM ${i.identifier(t)} WHERE ${$(t,S)} = ${e} AND ${f} AND ${u} NOT IN (SELECT ${B($("j","t"))} FROM ${j(n,r)})`]}case"postgres":{const f=i.identifier("__source__"),u=i.identifier("__purged__"),c=i`EXISTS (SELECT 1 FROM ${f})`;return[i`WITH ${f} AS (${Rt(n,s)}), ${u} AS (${M(t,e,c)} RETURNING 1) ${a(i`${c} AND (SELECT COUNT(*) FROM ${u}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=v(n,s);return[M(t,e,f),i`${a(f)} ON CONFLICT DO NOTHING`]}}},Ot={uniqueKeyMissing:!1,unmappedSkipped:0},ft=new Set,ut=(n,t)=>{ft.has(n)||(ft.add(n),console.warn(`[@lunora/sql-store] ${t}`))},ct=100,dt=3,K=async(n,t,e,r=0)=>{const{companion:s,definition:o,index:a,tableName:f}=e,u={done:!0,last:r,left:0};if((await p(n,t,t.tableExists(f))).length===0)return u;const d=await p(n,t,bt(s,ct,r));if(d.length===0)return u;const w=Math.max(...d.map(_=>Number(_.rowid))),E=Ut(d),l=await J(n,t,f,[...E.keys()]),m=[];for(const[_,nt]of E){const P=l.get(_),et=P===void 0?void 0:Q(o,P),it=_t(t,f,_,P);m.push(...et?mt(s,_,X(et,a),{guard:it,unmappedRowids:nt}):pt(s,_,{guard:it,unmappedRowids:nt}))}await A(n,t,m);const R=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(s)} WHERE ${$(s,"rowid")} > ${Math.max(0,r)} AND ${$(s,"rowid")} <= ${w}`);return{done:d.length<ct,last:w,left:Number(R[0]?.n??0)}},en=async(n,t,e)=>{let r=0,s=0;for(;;){let o=await K(n,t,e,r);for(let a=1;o.left>0&&a<dt;a+=1)o=await K(n,t,e,r);if(o.left>0&&(s+=o.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(o.left)} row(s) lost every one of ${String(dt)} attempts to a concurrent write and were left for a later pass.`)),o.done)return s;r=o.last}},rn=async(n,t,e,r)=>r==="step"?(await K(n,t,e),Ot):{uniqueKeyMissing:!1,unmappedSkipped:await en(n,t,e)},G=n=>`${n}__btree`,sn=async(n,t,e)=>{const r=Z(t,e),s=await C(n,t,e,r.name);if(s!=="valid"){if(s==="absent"&&(await p(n,t,i`SELECT 1 AS ${i.identifier("present")} FROM ${i.identifier(e)} LIMIT 1`)).length===0)try{await V(n,t,{...r,concurrently:!1}),await L(n,t,e,G(e));return}catch(a){if(await C(n,t,e,r.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},on=async(n,t,e)=>{const r=$(e,S),s=$(e,g);return(await p(n,t,i`SELECT ${r} AS ${i.identifier("id")}, ${s} AS ${i.identifier("token")}, COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(e)} GROUP BY ${r}, ${s} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},an=(n,t,{count:e,id:r,token:s})=>{const o=i`${$(t,S)} = ${r} AND ${$(t,g)} = ${s}`;switch(n.name){case"mysql":return i`DELETE FROM ${i.identifier(t)} WHERE ${o} LIMIT ${i.raw(String(e-1))}`;case"postgres":return i`DELETE FROM ${i.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${i.identifier(t)} WHERE ${o} OFFSET 1))`;default:return i`DELETE FROM ${i.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${i.identifier(t)} WHERE ${o} LIMIT -1 OFFSET 1)`}},fn=async(n,t,e,r)=>{const{companion:s,definition:o,index:a,tableName:f}=e;for(const d of r)await T(n,t,an(t,s,d));const u=[...new Set(r.map(d=>d.id))],c=await J(n,t,f,u);for(const d of u){const w=c.get(d),E=w===void 0?void 0:Q(o,w);if(w!==void 0&&E){const l=[...Tt(E,a)];await A(n,t,Nt(t,s,d,l,{row:w,table:f}));continue}await T(n,t,M(s,d,_t(t,f,d,w)))}},un=async(n,t,e)=>t.name!=="mysql"?"":(await p(n,t,i`SELECT COLUMN_NAME AS ${i.identifier("name")}, COLLATION_NAME AS ${i.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${S})`)).filter(s=>!String(s.collation).endsWith("_bin")).map(s=>` Its ${String(s.name)} column uses ${String(s.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(s.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),cn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const r=$(e,S),s=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM (SELECT 1 AS ${i.identifier("x")} FROM ${i.identifier(e)} GROUP BY LEFT(${r}, ${i.raw(String(z))}), ${$(e,g)} HAVING COUNT(DISTINCT ${r}) > 1) AS ${i.identifier("shared")}`);return Number(s[0]?.n??0)},dn=async(n,t,e)=>{const r=Z(t,e),s=await C(n,t,e,r.name);if(s==="valid")return"valid";s==="invalid"&&await L(n,t,e,r.name);try{return await V(n,t,r),"built"}catch(o){const a=await C(n,t,e,r.name);if(a==="valid")return"valid";if(a==="invalid"&&await L(n,t,e,r.name),!t.isUniqueViolation(o))throw o;return"refused"}},$t=3,$n=async(n,t,e)=>{const{companion:r}=e,s=await un(n,t,r);let o="";s!==""&&console.warn(`[@lunora/sql-store] search companion "${r}" folds case and accents in its unique key.${s}`);for(let a=0;a<$t;a+=1){const f=await dn(n,t,r);if(f==="valid")return await L(n,t,r,G(r)),!0;if(f==="refused"){const u=await on(n,t,r);if(u.length>0)await fn(n,t,e,u);else{const c=await cn(n,t,r);o=c>0?` ${String(c)} token(s) are held by document ids that agree on their first ${String(z)} characters, which the key cannot tell apart; shorten those ids.`:s}}}return await C(n,t,r,Z(t,r).name)==="valid"?(await L(n,t,r,G(r)),!0):(console.warn(`[@lunora/sql-store] search companion "${r}" still has no unique key after ${String($t)} attempts: writes keep working, but two backfills racing over one row can index it twice.${o}`),!1)},wn=async(n,t,e,r)=>r==="step"?Ot:{uniqueKeyMissing:!await $n(n,t,e),unmappedSkipped:0},Sn=(n,t)=>t?i`${i.identifier(g)} LIKE ${`${n}%`}`:i`${i.identifier(g)} = ${n}`,At=(n,t)=>{const e=t.filters.map(r=>i`m.${rt(r.field)} = ${Wt(r.value)}`);return n.softDeleteMode&&e.push(i`m.${rt(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(i`(${t.scope})`),e},It=async(n,t,e,r,s,o,a)=>{const f=At(e,s);let u=i`SELECT m.* FROM (${a}) s JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = s.${i.identifier(S)}`;return f.length>0&&(u=i`${u} WHERE ${i.join(f,i` AND `)}`),u=i`${u} ORDER BY s.${i.identifier("__score__")} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`,ht(e,await p(n,t,u))},En=async(n,t,e,r,s,o)=>{const a=b(s.query,q(s.definition.language));if(a.length===0)return[];const f=U(r,s.indexName),u=a.length-1,c=a.map((m,R)=>Sn(m,R===u)),d=i.join(c,i` OR `),w=c.map(m=>i`SUM(CASE WHEN ${m} THEN ${i.identifier(O)} ELSE 0 END)`),E=i.join(w.map(m=>i`${m} > 0`),i` AND `),l=i`SELECT ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM ${i.identifier(f)} WHERE ${d} GROUP BY ${i.identifier(S)} HAVING ${E}`;return It(n,t,e,r,s,o,l)},ln=async(n,t,e,r,s,o)=>{const a=b(s.query,q(s.definition.language));if(a.length===0)return[];const f=U(r,s.indexName),u=`${f}__vocab`,c=a.length-1,d=a.map((l,m)=>{const R=Qt(l,m===c),_=R.exact?i`${i.identifier("term")} = ${R.lower}`:i`${i.identifier("term")} >= ${R.lower} AND ${i.identifier("term")} < ${R.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(m))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(u)} WHERE ${_} GROUP BY ${i.identifier("doc")}`}),w=a.map((l,m)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(m))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),E=i`SELECT f.${i.identifier(S)} AS ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM (${Ht(d)}) u JOIN ${i.identifier(f)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(S)} HAVING ${i.join(w.map(l=>i`${l} > 0`),i` AND `)}`;return It(n,t,e,r,s,o,E)},mn=async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch,f=b(s.query,q(s.definition.language));if(!a||f.length===0)return[];const u=U(r,s.indexName),c=[a.matches(u,f),...At(e,s)],d=i`SELECT m.* FROM ${i.identifier(u)} JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = ${i.identifier(u)}.${i.identifier(S)} WHERE ${i.join(c,i` AND `)} ORDER BY ${a.rank(u,f)} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`;return ht(e,await p(n,t,d))},pn={ensureCompanion:async(n,t,e)=>{const{integer:r,key:s}=t.companionTypes;await T(n,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(e)} (${i.identifier(g)} ${i.raw(s)} NOT NULL, ${i.identifier(S)} ${i.raw(s)} NOT NULL, ${i.identifier(O)} ${i.raw(r)} NOT NULL)`),await V(n,t,{columns:x(t,S,191),name:`${e}__by_id`,table:e,unique:!1}),await sn(n,t,e)},indexDocument:async(n,t,e,r,s,o)=>{const a=[...Tt(r,s)];await A(n,t,Nt(t,e,String(o.row.id),a,o))},migrate:wn,name:"inverted",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,M(e,r,k(s,r)))},runSearch:En},hn={ensureCompanion:async(n,t,e)=>{await A(n,t,kt(e))},indexDocument:async(n,t,e,r,s,o)=>{await A(n,t,mt(e,String(o.row.id),X(r,s),{guard:v(t,o)}))},migrate:rn,name:"fts5",purgeDocument:async(n,t,e,r,s)=>{await A(n,t,pt(e,r,{guard:k(s,r)}))},runSearch:ln},gn={ensureCompanion:async(n,t,e)=>{const r=t.nativeTextSearch;if(r){await T(n,t,r.createCompanion(e,t.companionTypes.key));for(const s of r.createIndexes(e))await T(n,t,s)}},indexDocument:async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch;a&&await T(n,t,a.indexDocument(e,String(o.row.id),X(r,s),v(t,o)))},name:"native",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,M(e,r,k(s,r)))},runSearch:mn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?gn:t.supportsFts5?hn:pn,H=(n,t)=>`${vt(n)}/${I(n,t).name}`,tt=function*(n){for(const[t,e]of Object.entries(n.tables)){const r=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!r))for(const s of r)yield[t,e,s]}},N=(n,t)=>U(n,t.name),Tn=async(n,t,e,r)=>{const s=N(e,r);return lt(await F(n,t,s),H(r,t)).finished?!0:Ft(n,t,s)},Fn=async(n,t,e,r,s,o)=>{if(!await Tn(n,t,r,s.definition))throw new h("SEARCH_INDEX_BUILDING",`search index "${s.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(s.definition,t).runSearch(n,t,e,r,s,o)},wt=n=>n.slice(n.lastIndexOf("/")+1),St=200,Et=5,yn=async(n,t,e,r)=>{const s=[...r.keys()],o=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${i.identifier("id")} >= ${s[0]} AND ${i.identifier("id")} <= ${s.at(-1)} ORDER BY ${i.identifier("id")} ASC`),a=new Map;for(const f of o){const u=f.id,c=r.get(u)?.row;c&&yt.some(d=>String(c[d])!==String(f[d]))&&a.set(u,{row:f})}return a},Y=async(n,t,e,r,s,o,a)=>{const f=I(o,t);let u=a;for(let c=0;u.size>0&&c<Et;c+=1){for(const{document:d,row:w}of u.values()){const E=d??Q(e,w);E&&await f.indexDocument(n,t,s,E,o,{row:w,table:r})}u=await yn(n,t,r,u)}u.size>0&&console.warn(`[@lunora/sql-store] search index "${s}": ${String(u.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,r,s)=>{const o=N(r,s),a=H(s,t),f=lt(await F(n,t,o),a);if(f.finished)return!0;if(f.wipe&&await D(n,t,o,void 0,!1,a),(await p(n,t,t.tableExists(r))).length===0)return await D(n,t,o,void 0,!0,a),!0;const c=await xt(n,t,r,f.cursor,St),d=c.findLast(l=>typeof l.id=="string")?.id,w=new Map;for(const l of c)typeof l.id=="string"&&w.set(l.id,{row:l});await Y(n,t,e,r,o,s,w);const E=c.length<St;return await D(n,t,o,d??f.cursor,E,a),E},Lt=async(n,t,e)=>{await Dt(n,e);for(const[r,,s]of tt(t)){const o=N(r,s),a=H(s,e),f=await F(n,e,o);f.profile!==void 0&&wt(f.profile)!==wt(a)&&(await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(o)}`),await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(Pt(o))}`),await qt(n,e,o)),await I(s,e).ensureCompanion(n,e,o)}},Rn=async(n,t,e,r,s)=>{const o=N(r,s);if((await F(n,t,o)).profile!==void 0)return;let f=0;(await p(n,t,t.tableExists(r))).length>0&&await Kt(n,t,e,r,()=>{f+=1},{limit:1}),await D(n,t,o,void 0,f===0,H(s,t))},Mt=async(n,t,e,r,s,o)=>await I(s,t).migrate?.(n,t,{companion:N(r,s),definition:e,index:s,tableName:r},o)??{uniqueKeyMissing:!1,unmappedSkipped:0},bn=async(n,t,e)=>{await Lt(n,t,e);for(const[r,s,o]of tt(t)){if(await Mt(n,e,s,r,o,"step"),o.staged){await Rn(n,e,s,r,o);continue}await Ct(n,e,s,r,o)}},Un=async(n,t,e)=>{const r={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[s,o,a]of tt(t)){const f=await Mt(n,e,o,s,a,"drain");r.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&r.uniqueKeyMissing.push(N(s,a));let u=!1;for(;!u;)u=await Ct(n,e,o,s,a)}return r},kn=n=>{const{dialect:t,exec:e,schema:r}=n;return async(s,o,a)=>{const f=r.tables[s],u=f?.searchIndexes;if(!(!f||!u||u.length===0))for(const c of u){if(nn(a?.previous,a?.document,c))continue;const d=N(s,c);if(a){await Y(e,t,f,s,d,c,new Map([[o,{document:a.document,row:{...a.written,id:o}}]]));continue}await I(c,t).purgeDocument(e,t,d,o,s);const E=(await J(e,t,s,[o])).get(o);E!==void 0&&await Y(e,t,f,s,d,c,new Map([[o,{row:E}]]))}}};export{Cn as A,vn as C,Dn as R,qn as T,Fn as a,Un as b,kn as c,Mn as d,bn as r,st as u,Ln as x};
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{q,c as vt,m as Dt,r as F,a as qt,l as lt,w as D,b as Ft}from"./ctx-db-search-state-C4l9QBq-.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ut,ftsWriteDocument as mt,ftsPurgeDocument as pt,ftsCompanionDdl as kt,unionAll as Ht,ftsRowidMapName as Pt}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{q as p,O as Bt,u as jt,l as Q,a as A,i as C,c as V,j as L,b as T,m as ht,e as rt,x as Wt,r as xt,z as Kt}from"./sql-exec-CkHeSf_v.mjs";const Gt=n=>{const t=atob(n),e=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(e)},Yt=()=>new h("BAD_REQUEST","invalid cursor"),st=16,ot=8,y=1024,b=(n,t)=>t.query(n),Qt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",r=(e.codePointAt(0)??0)+1;if(r>=55296&&r<=57343||r>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(r)}},Cn=(n,t,e)=>{const r={eq:(s,o)=>{if(!n.definition.filterFields?.includes(s))throw new h("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=ot)throw new h("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(ot)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:o}),r},search:(s,o)=>{const a=n;if(s!==a.definition.field)throw new h("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${s}"`);const f=b(o,e).length;if(f>st)throw new h("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=s,a.query=o,a.hasQuery=!0,r}};return r},Ln=n=>{if(n.length>y)throw new h("BAD_REQUEST",`more than ${String(y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Mn=n=>Math.min(n.offset+n.numItems+1,y),Vt=n=>btoa(`search:${String(n)}`),Xt=n=>{let t;try{t=Gt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},vn=n=>{if(typeof n.endCursor=="string")throw new h("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new h("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Xt(n.cursor):0;if(e===void 0)throw Yt();if(e+t>=y)throw new h("BAD_REQUEST",`search pagination reaches the ${String(y)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,y-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},Dn=(n,t)=>{const e=t.offset+t.numItems,r=t.numItems>0&&n.length>e;return{continueCursor:r?Vt(e):null,isDone:!r,page:n.slice(t.offset,e)}},qn=n=>{if(n===void 0)return y+1;if(!Number.isFinite(n))return y;const t=Math.max(0,Math.floor(n));if(t>y)throw new h("BAD_REQUEST",`search returns at most ${String(y)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},Jt=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const r of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[r]}return e},U=(n,t)=>`${n}__fts_${t}`,S="__id__",g="__token__",O="__n__",zt=1e3,Zt=(n,t)=>t.document(n),W=(n,t)=>Jt(n,t),tn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",nn=(n,t,e)=>n!==void 0&&t!==void 0&&W(n,e.field)===W(t,e.field),gt=(n,t)=>Zt(tn(W(n,t.field)),q(t.language)).slice(0,zt),X=(n,t)=>gt(n,t).join(" "),Tt=(n,t)=>{const e=new Map;for(const r of gt(n,t))e.set(r,(e.get(r)??0)+1);return e},yt=[Bt,"_creationTime"],at=50,$=(n,t)=>i`${i.identifier(n)}.${i.identifier(t)}`,M=(n,t,e)=>i`DELETE FROM ${i.identifier(n)} WHERE ${$(n,S)} = ${t}${e===void 0?i``:i` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const r=yt.map(s=>i` AND ${jt(n.name,$(e,s),t[s]??null)}`);return i`SELECT 1 FROM ${i.identifier(e)} WHERE ${$(e,"id")} = ${t.id}${i.join(r)}${n.name==="postgres"?i` FOR SHARE`:i``}`},v=(n,t)=>i`EXISTS (${Rt(n,t)})`,k=(n,t)=>i`NOT EXISTS (SELECT 1 FROM ${i.identifier(n)} WHERE ${$(n,"id")} = ${t})`,_t=(n,t,e,r)=>r===void 0?k(t,e):v(n,{row:r,table:t}),J=async(n,t,e,r)=>{const s=new Map;for(let o=0;o<r.length;o+=at){const a=r.slice(o,o+at),f=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${$(e,"id")} IN (${i.join(a.map(u=>i`${u}`),i`, `)})`);for(const u of f)s.set(String(u.id),u)}return s},x=(n,t,e)=>n.name==="mysql"?i`${i.identifier(t)}(${i.raw(String(e))})`:n.textPatternOperatorClass===void 0?i`${i.identifier(t)}`:i`${i.identifier(t)} ${i.raw(n.textPatternOperatorClass)}`,z=512,Z=(n,t)=>({columns:i`${x(n,g,256)}, ${x(n,S,z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),B=n=>i`${n} COLLATE utf8mb4_0900_bin`,j=(n,t)=>{const e=JSON.stringify(t.map(([r,s])=>({o:s,t:r})));switch(n.name){case"mysql":return i`JSON_TABLE(${e}, '$[*]' COLUMNS (${i.identifier("t")} VARCHAR(256) PATH '$.t', ${i.identifier("o")} INT PATH '$.o')) AS ${i.identifier("j")}`;case"postgres":return i`json_to_recordset(${e}::text::json) AS ${i.identifier("j")}(${i.identifier("t")} text, ${i.identifier("o")} integer)`;default:return i`(SELECT json_extract(${$("e","value")}, '$.t') AS ${i.identifier("t")}, json_extract(${$("e","value")}, '$.o') AS ${i.identifier("o")} FROM json_each(${e}) AS ${i.identifier("e")}) AS ${i.identifier("j")}`}},Nt=(n,t,e,r,s)=>{const o=i.join([g,S,O].map(f=>i.identifier(f)),i`, `),a=f=>i`INSERT INTO ${i.identifier(t)} (${o}) SELECT ${$("j","t")}, ${e}, ${$("j","o")} FROM ${j(n,r)} WHERE ${f}`;switch(n.name){case"mysql":{const f=v(n,s),u=$(t,g),c=i.identifier("held");return[i`${a(i`${f} AND NOT EXISTS (SELECT 1 FROM ${i.identifier(t)} AS ${c} WHERE ${$("held",S)} = ${e} AND ${$("held",g)} = ${B($("j","t"))})`)} ON DUPLICATE KEY UPDATE ${$(t,O)} = ${$(t,O)}`,i`UPDATE ${i.identifier(t)} JOIN ${j(n,r)} ON ${u} = ${B($("j","t"))} SET ${$(t,O)} = ${$("j","o")} WHERE ${$(t,S)} = ${e} AND ${f}`,i`DELETE FROM ${i.identifier(t)} WHERE ${$(t,S)} = ${e} AND ${f} AND ${u} NOT IN (SELECT ${B($("j","t"))} FROM ${j(n,r)})`]}case"postgres":{const f=i.identifier("__source__"),u=i.identifier("__purged__"),c=i`EXISTS (SELECT 1 FROM ${f})`;return[i`WITH ${f} AS (${Rt(n,s)}), ${u} AS (${M(t,e,c)} RETURNING 1) ${a(i`${c} AND (SELECT COUNT(*) FROM ${u}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=v(n,s);return[M(t,e,f),i`${a(f)} ON CONFLICT DO NOTHING`]}}},Ot={uniqueKeyMissing:!1,unmappedSkipped:0},ft=new Set,ut=(n,t)=>{ft.has(n)||(ft.add(n),console.warn(`[@lunora/sql-store] ${t}`))},ct=100,dt=3,K=async(n,t,e,r=0)=>{const{companion:s,definition:o,index:a,tableName:f}=e,u={done:!0,last:r,left:0};if((await p(n,t,t.tableExists(f))).length===0)return u;const d=await p(n,t,bt(s,ct,r));if(d.length===0)return u;const w=Math.max(...d.map(_=>Number(_.rowid))),E=Ut(d),l=await J(n,t,f,[...E.keys()]),m=[];for(const[_,nt]of E){const P=l.get(_),et=P===void 0?void 0:Q(o,P),it=_t(t,f,_,P);m.push(...et?mt(s,_,X(et,a),{guard:it,unmappedRowids:nt}):pt(s,_,{guard:it,unmappedRowids:nt}))}await A(n,t,m);const R=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(s)} WHERE ${$(s,"rowid")} > ${Math.max(0,r)} AND ${$(s,"rowid")} <= ${w}`);return{done:d.length<ct,last:w,left:Number(R[0]?.n??0)}},en=async(n,t,e)=>{let r=0,s=0;for(;;){let o=await K(n,t,e,r);for(let a=1;o.left>0&&a<dt;a+=1)o=await K(n,t,e,r);if(o.left>0&&(s+=o.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(o.left)} row(s) lost every one of ${String(dt)} attempts to a concurrent write and were left for a later pass.`)),o.done)return s;r=o.last}},rn=async(n,t,e,r)=>r==="step"?(await K(n,t,e),Ot):{uniqueKeyMissing:!1,unmappedSkipped:await en(n,t,e)},G=n=>`${n}__btree`,sn=async(n,t,e)=>{const r=Z(t,e),s=await C(n,t,e,r.name);if(s!=="valid"){if(s==="absent"&&(await p(n,t,i`SELECT 1 AS ${i.identifier("present")} FROM ${i.identifier(e)} LIMIT 1`)).length===0)try{await V(n,t,{...r,concurrently:!1}),await L(n,t,e,G(e));return}catch(a){if(await C(n,t,e,r.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},on=async(n,t,e)=>{const r=$(e,S),s=$(e,g);return(await p(n,t,i`SELECT ${r} AS ${i.identifier("id")}, ${s} AS ${i.identifier("token")}, COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(e)} GROUP BY ${r}, ${s} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},an=(n,t,{count:e,id:r,token:s})=>{const o=i`${$(t,S)} = ${r} AND ${$(t,g)} = ${s}`;switch(n.name){case"mysql":return i`DELETE FROM ${i.identifier(t)} WHERE ${o} LIMIT ${i.raw(String(e-1))}`;case"postgres":return i`DELETE FROM ${i.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${i.identifier(t)} WHERE ${o} OFFSET 1))`;default:return i`DELETE FROM ${i.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${i.identifier(t)} WHERE ${o} LIMIT -1 OFFSET 1)`}},fn=async(n,t,e,r)=>{const{companion:s,definition:o,index:a,tableName:f}=e;for(const d of r)await T(n,t,an(t,s,d));const u=[...new Set(r.map(d=>d.id))],c=await J(n,t,f,u);for(const d of u){const w=c.get(d),E=w===void 0?void 0:Q(o,w);if(w!==void 0&&E){const l=[...Tt(E,a)];await A(n,t,Nt(t,s,d,l,{row:w,table:f}));continue}await T(n,t,M(s,d,_t(t,f,d,w)))}},un=async(n,t,e)=>t.name!=="mysql"?"":(await p(n,t,i`SELECT COLUMN_NAME AS ${i.identifier("name")}, COLLATION_NAME AS ${i.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${S})`)).filter(s=>!String(s.collation).endsWith("_bin")).map(s=>` Its ${String(s.name)} column uses ${String(s.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(s.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),cn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const r=$(e,S),s=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM (SELECT 1 AS ${i.identifier("x")} FROM ${i.identifier(e)} GROUP BY LEFT(${r}, ${i.raw(String(z))}), ${$(e,g)} HAVING COUNT(DISTINCT ${r}) > 1) AS ${i.identifier("shared")}`);return Number(s[0]?.n??0)},dn=async(n,t,e)=>{const r=Z(t,e),s=await C(n,t,e,r.name);if(s==="valid")return"valid";s==="invalid"&&await L(n,t,e,r.name);try{return await V(n,t,r),"built"}catch(o){const a=await C(n,t,e,r.name);if(a==="valid")return"valid";if(a==="invalid"&&await L(n,t,e,r.name),!t.isUniqueViolation(o))throw o;return"refused"}},$t=3,$n=async(n,t,e)=>{const{companion:r}=e,s=await un(n,t,r);let o="";s!==""&&console.warn(`[@lunora/sql-store] search companion "${r}" folds case and accents in its unique key.${s}`);for(let a=0;a<$t;a+=1){const f=await dn(n,t,r);if(f==="valid")return await L(n,t,r,G(r)),!0;if(f==="refused"){const u=await on(n,t,r);if(u.length>0)await fn(n,t,e,u);else{const c=await cn(n,t,r);o=c>0?` ${String(c)} token(s) are held by document ids that agree on their first ${String(z)} characters, which the key cannot tell apart; shorten those ids.`:s}}}return await C(n,t,r,Z(t,r).name)==="valid"?(await L(n,t,r,G(r)),!0):(console.warn(`[@lunora/sql-store] search companion "${r}" still has no unique key after ${String($t)} attempts: writes keep working, but two backfills racing over one row can index it twice.${o}`),!1)},wn=async(n,t,e,r)=>r==="step"?Ot:{uniqueKeyMissing:!await $n(n,t,e),unmappedSkipped:0},Sn=(n,t)=>t?i`${i.identifier(g)} LIKE ${`${n}%`}`:i`${i.identifier(g)} = ${n}`,At=(n,t)=>{const e=t.filters.map(r=>i`m.${rt(r.field)} = ${Wt(r.value)}`);return n.softDeleteMode&&e.push(i`m.${rt(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(i`(${t.scope})`),e},It=async(n,t,e,r,s,o,a)=>{const f=At(e,s);let u=i`SELECT m.* FROM (${a}) s JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = s.${i.identifier(S)}`;return f.length>0&&(u=i`${u} WHERE ${i.join(f,i` AND `)}`),u=i`${u} ORDER BY s.${i.identifier("__score__")} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`,ht(e,await p(n,t,u))},En=async(n,t,e,r,s,o)=>{const a=b(s.query,q(s.definition.language));if(a.length===0)return[];const f=U(r,s.indexName),u=a.length-1,c=a.map((m,R)=>Sn(m,R===u)),d=i.join(c,i` OR `),w=c.map(m=>i`SUM(CASE WHEN ${m} THEN ${i.identifier(O)} ELSE 0 END)`),E=i.join(w.map(m=>i`${m} > 0`),i` AND `),l=i`SELECT ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM ${i.identifier(f)} WHERE ${d} GROUP BY ${i.identifier(S)} HAVING ${E}`;return It(n,t,e,r,s,o,l)},ln=async(n,t,e,r,s,o)=>{const a=b(s.query,q(s.definition.language));if(a.length===0)return[];const f=U(r,s.indexName),u=`${f}__vocab`,c=a.length-1,d=a.map((l,m)=>{const R=Qt(l,m===c),_=R.exact?i`${i.identifier("term")} = ${R.lower}`:i`${i.identifier("term")} >= ${R.lower} AND ${i.identifier("term")} < ${R.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(m))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(u)} WHERE ${_} GROUP BY ${i.identifier("doc")}`}),w=a.map((l,m)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(m))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),E=i`SELECT f.${i.identifier(S)} AS ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM (${Ht(d)}) u JOIN ${i.identifier(f)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(S)} HAVING ${i.join(w.map(l=>i`${l} > 0`),i` AND `)}`;return It(n,t,e,r,s,o,E)},mn=async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch,f=b(s.query,q(s.definition.language));if(!a||f.length===0)return[];const u=U(r,s.indexName),c=[a.matches(u,f),...At(e,s)],d=i`SELECT m.* FROM ${i.identifier(u)} JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = ${i.identifier(u)}.${i.identifier(S)} WHERE ${i.join(c,i` AND `)} ORDER BY ${a.rank(u,f)} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`;return ht(e,await p(n,t,d))},pn={ensureCompanion:async(n,t,e)=>{const{integer:r,key:s}=t.companionTypes;await T(n,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(e)} (${i.identifier(g)} ${i.raw(s)} NOT NULL, ${i.identifier(S)} ${i.raw(s)} NOT NULL, ${i.identifier(O)} ${i.raw(r)} NOT NULL)`),await V(n,t,{columns:x(t,S,191),name:`${e}__by_id`,table:e,unique:!1}),await sn(n,t,e)},indexDocument:async(n,t,e,r,s,o)=>{const a=[...Tt(r,s)];await A(n,t,Nt(t,e,String(o.row.id),a,o))},migrate:wn,name:"inverted",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,M(e,r,k(s,r)))},runSearch:En},hn={ensureCompanion:async(n,t,e)=>{await A(n,t,kt(e))},indexDocument:async(n,t,e,r,s,o)=>{await A(n,t,mt(e,String(o.row.id),X(r,s),{guard:v(t,o)}))},migrate:rn,name:"fts5",purgeDocument:async(n,t,e,r,s)=>{await A(n,t,pt(e,r,{guard:k(s,r)}))},runSearch:ln},gn={ensureCompanion:async(n,t,e)=>{const r=t.nativeTextSearch;if(r){await T(n,t,r.createCompanion(e,t.companionTypes.key));for(const s of r.createIndexes(e))await T(n,t,s)}},indexDocument:async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch;a&&await T(n,t,a.indexDocument(e,String(o.row.id),X(r,s),v(t,o)))},name:"native",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,M(e,r,k(s,r)))},runSearch:mn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?gn:t.supportsFts5?hn:pn,H=(n,t)=>`${vt(n)}/${I(n,t).name}`,tt=function*(n){for(const[t,e]of Object.entries(n.tables)){const r=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!r))for(const s of r)yield[t,e,s]}},N=(n,t)=>U(n,t.name),Tn=async(n,t,e,r)=>{const s=N(e,r);return lt(await F(n,t,s),H(r,t)).finished?!0:Ft(n,t,s)},Fn=async(n,t,e,r,s,o)=>{if(!await Tn(n,t,r,s.definition))throw new h("SEARCH_INDEX_BUILDING",`search index "${s.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(s.definition,t).runSearch(n,t,e,r,s,o)},wt=n=>n.slice(n.lastIndexOf("/")+1),St=200,Et=5,yn=async(n,t,e,r)=>{const s=[...r.keys()],o=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${i.identifier("id")} >= ${s[0]} AND ${i.identifier("id")} <= ${s.at(-1)} ORDER BY ${i.identifier("id")} ASC`),a=new Map;for(const f of o){const u=f.id,c=r.get(u)?.row;c&&yt.some(d=>String(c[d])!==String(f[d]))&&a.set(u,{row:f})}return a},Y=async(n,t,e,r,s,o,a)=>{const f=I(o,t);let u=a;for(let c=0;u.size>0&&c<Et;c+=1){for(const{document:d,row:w}of u.values()){const E=d??Q(e,w);E&&await f.indexDocument(n,t,s,E,o,{row:w,table:r})}u=await yn(n,t,r,u)}u.size>0&&console.warn(`[@lunora/sql-store] search index "${s}": ${String(u.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,r,s)=>{const o=N(r,s),a=H(s,t),f=lt(await F(n,t,o),a);if(f.finished)return!0;if(f.wipe&&await D(n,t,o,void 0,!1,a),(await p(n,t,t.tableExists(r))).length===0)return await D(n,t,o,void 0,!0,a),!0;const c=await xt(n,t,r,f.cursor,St),d=c.findLast(l=>typeof l.id=="string")?.id,w=new Map;for(const l of c)typeof l.id=="string"&&w.set(l.id,{row:l});await Y(n,t,e,r,o,s,w);const E=c.length<St;return await D(n,t,o,d??f.cursor,E,a),E},Lt=async(n,t,e)=>{await Dt(n,e);for(const[r,,s]of tt(t)){const o=N(r,s),a=H(s,e),f=await F(n,e,o);f.profile!==void 0&&wt(f.profile)!==wt(a)&&(await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(o)}`),await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(Pt(o))}`),await qt(n,e,o)),await I(s,e).ensureCompanion(n,e,o)}},Rn=async(n,t,e,r,s)=>{const o=N(r,s);if((await F(n,t,o)).profile!==void 0)return;let f=0;(await p(n,t,t.tableExists(r))).length>0&&await Kt(n,t,e,r,()=>{f+=1},{limit:1}),await D(n,t,o,void 0,f===0,H(s,t))},Mt=async(n,t,e,r,s,o)=>await I(s,t).migrate?.(n,t,{companion:N(r,s),definition:e,index:s,tableName:r},o)??{uniqueKeyMissing:!1,unmappedSkipped:0},bn=async(n,t,e)=>{await Lt(n,t,e);for(const[r,s,o]of tt(t)){if(await Mt(n,e,s,r,o,"step"),o.staged){await Rn(n,e,s,r,o);continue}await Ct(n,e,s,r,o)}},Un=async(n,t,e)=>{const r={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[s,o,a]of tt(t)){const f=await Mt(n,e,o,s,a,"drain");r.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&r.uniqueKeyMissing.push(N(s,a));let u=!1;for(;!u;)u=await Ct(n,e,o,s,a)}return r},kn=n=>{const{dialect:t,exec:e,schema:r}=n;return async(s,o,a)=>{const f=r.tables[s],u=f?.searchIndexes;if(!(!f||!u||u.length===0))for(const c of u){if(nn(a?.previous,a?.document,c))continue;const d=N(s,c);if(a){await Y(e,t,f,s,d,c,new Map([[o,{document:a.document,row:{...a.written,id:o}}]]));continue}await I(c,t).purgeDocument(e,t,d,o,s);const E=(await J(e,t,s,[o])).get(o);E!==void 0&&await Y(e,t,f,s,d,c,new Map([[o,{row:E}]]))}}};export{Cn as A,vn as C,Dn as R,qn as T,Fn as a,Un as b,kn as c,Mn as d,bn as r,st as u,Ln as x};
|
package/dist/packem_shared/{ctx-db-search-state-CaX6vwUz.mjs → ctx-db-search-state-C4l9QBq-.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{b as $,q as h}from"./sql-exec-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{b as $,q as h}from"./sql-exec-CkHeSf_v.mjs";const y=["de","en","es","fr","it","nl","none","pt"],L=i=>y.includes(i),R="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",A="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",q="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",F="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",N="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",_="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",b="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",C=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),x=/[\u0080-\u{10FFFF}]/u,H=/[\p{L}\p{N}]+/gu,O=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,g=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,j=i=>{if(!g.test(i))return[i];const n=[];let t=0;for(const r of i.matchAll(O)){const o=r.index,s=[...r[0]];if(o>t&&n.push(i.slice(t,o)),t=o+r[0].length,s.length===1){n.push(r[0]);continue}for(let a=0;a+1<s.length;a+=1)n.push(`${String(s[a])}${String(s[a+1])}`)}return t<i.length&&n.push(i.slice(t)),n},v=i=>x.test(i)?i.normalize("NFD").replaceAll(C,"").normalize("NFC").toLowerCase():i.toLowerCase(),p=i=>new Set(v(i).split(" ")),z={de:p(A),en:p(R),es:p(q),fr:p(F),it:p(N),nl:p(_),none:new Set,pt:p(b)},D=3,U=256,w=new Map,k=i=>{const n=i!==void 0&&L(i)?i:"none",t=w.get(n);if(t)return t;const r=z[n],o=a=>{const u=v(a),f=u.match(H)??[],l=(g.test(u)?f.flatMap(c=>j(c)):f).filter(c=>c.length<=U);return r.size===0?l:l.filter(c=>!r.has(c))},s={document:o,profile:`${n}-v${String(D)}`,query:a=>{const u=o(a),f=new Set,l=[];for(let c=u.length-1;c>=0;c-=1){const m=u[c];f.has(m)||(f.add(m),l.push(m))}return l.toReversed()}};return w.set(n,s),s},W=i=>`${k(i.language).profile}:${i.field}`,S=i=>{const n=i.slice(i.indexOf(":")+1),t=n.lastIndexOf("/");return t===-1?n:n.slice(0,t)},V=(i,n)=>i.profile!==n?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},M=(i,n)=>typeof i=="string"&&S(i)===S(n),d="__lunora_search_state",K=async(i,n)=>{const{integer:t,key:r}=n.companionTypes,o=async(s,a)=>{try{await $(i,n,e`ALTER TABLE ${e.identifier(d)} ADD COLUMN ${e.identifier(s)} ${e.raw(a)}`)}catch{}};await $(i,n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (${e.identifier("companion")} ${e.raw(r)} PRIMARY KEY, ${e.identifier("cursor")} ${e.raw(r)}, ${e.identifier("done")} ${e.raw(t)} NOT NULL DEFAULT 0, ${e.identifier("profile")} ${e.raw(r)}, ${e.identifier("covered")} ${e.raw(t)} NOT NULL DEFAULT 0)`),await o("profile",r),await o("covered",`${t} NOT NULL DEFAULT 0`),await $(i,n,e`UPDATE ${e.identifier(d)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},T=i=>i===1||i===!0||i==="1",P=async(i,n,t)=>{const r=await h(i,n,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`);return T(r[0]?.covered)},Y=async(i,n,t)=>{await $(i,n,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`)},X=async(i,n,t)=>{const o=(await h(i,n,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`))[0];if(!o)return{cursor:void 0,done:!1,profile:void 0};const{cursor:s,profile:a}=o;return{cursor:typeof s=="string"?s:void 0,done:T(o.done),profile:typeof a=="string"?a:void 0}},G=async(i,n,t,r,o,s)=>{const a=r??null,u=await h(i,n,e`SELECT ${e.identifier("profile")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`),f=M(u[0]?.profile,s),l=o?1:0,c=o||!f?e`${e.identifier("covered")} = ${l}`:e`${e.identifier("covered")} = ${e.identifier("covered")}`,m=e`UPDATE ${e.identifier(d)} SET ${e.identifier("cursor")} = ${a}, ${e.identifier("done")} = ${l}, ${e.identifier("profile")} = ${s}, ${c} WHERE ${e.identifier("companion")} = ${t}`;if(u.length>0){await $(i,n,m);return}try{await $(i,n,e`INSERT INTO ${e.identifier(d)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${t}, ${a}, ${o?1:0}, ${s}, ${o?1:0})`)}catch(E){if(!n.isUniqueViolation(E))throw E;await $(i,n,m)}};export{d as S,Y as a,P as b,W as c,V as l,K as m,k as q,X as r,G as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as l,M as o,O as n,e as r,c as t,d,l as i,m as u,j as R,o as f,z as q,i as c,n as C,u as S,h as m,k as p,p as x,w as I,f as E,q as h,g as w,b as A,r as O,a as _,x as B,s as N,v as y,t as z}from"./sql-exec-CkHeSf_v.mjs";import"./value-codec-C52YW-Do.mjs";export{l as BACKFILL_BATCH_SIZE,o as MAX_BOUND_PARAMETERS,n as OCC_VERSION_COLUMN,r as columnRefSql,t as createIndexIfNotExists,d as decodeGlobalRow,i as decodeRow,u as decodeRows,R as dropIndexIfExists,f as fieldRefSql,q as forEachRowPaged,c as indexState,C as nextRowVersion,S as nullSafeEqualsSql,m as pathContainsNeedle,p as pathInList,x as pathTextReference,I as pathTypeGuardSql,E as qualifiedColumnRefSql,h as queryAll,w as queryBatch,A as queryRun,O as readRowsPage,_ as runInOrder,B as serializeColumnValue,N as serializeDocumentColumn,y as serializeFieldValue,z as tableColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as k}from"@lunora/errors";import{needsWireEncoding as _,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as p}from"drizzle-orm";import{runSqlGlobalTableMigrations as E}from"./runSqlGlobalTableMigrations-C24sSQdc.mjs";import{r as L,d as $,M as w,q as O}from"./sql-exec-CkHeSf_v.mjs";const D=200,m=(o,t)=>{const n=e=>o.tables[e]?.shardMode?.kind==="global";return t&&t.length>0?t.filter(e=>n(e)):Object.keys(o.tables).filter(e=>n(e))},F=o=>_(o)?A(o):o,Y=async function*(o,t,n,e){const i=m(t,e.tables),r=e.batchSize??D;await E(o,t,n);for(const s of i){const d=t.tables[s];let c,a=!0;for(;a;){const f=await L(o,n,s,c,r);for(const u of f)yield{doc:F($(d,u)),table:s};const l=f.at(-1);l!==void 0&&(c=String(l.id)),a=f.length===r}}},h=o=>o?._meta?.column?.notNull===!1,N=(o,t)=>{const n=new Set;for(const[e,i]of Object.entries(o.shape)){if(t[e]!==null||i.kind!=="optional"||h(i))continue;const r=i._meta?.inner;h(r)||n.add(e)}return n.size===0?t:Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e)))},T=new Set(["_creationTime","_id"]),M=(o,t)=>Object.keys(t).find(n=>!T.has(n)&&!Object.hasOwn(o.shape,n)),C=o=>{const t=o._id,n=o._creationTime;if(t!==void 0&&(typeof t!="string"||t===""))return'field "_id": must be a non-empty string';if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)))return'field "_creationTime": must be a finite number'},j=(o,t,n)=>{const e=o.tables[t];if(!e)return`unknown table: ${t}`;const i=M(e,n);if(i!==void 0)return`unexpected field "${i}": not declared in table "${t}"`;const r=C(n);if(r!==void 0)return r;for(const[s,d]of Object.entries(e.shape)){const c=n[s],a=d.kind==="optional";if(c===void 0&&a)continue;const f=d.parse;if(typeof f=="function")try{f(c)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${s}": ${u}`}}},v=async(o,t,n,e,i,r)=>{const s=Object.keys(t.tables).filter(c=>c!==i&&t.tables[c]?.shardMode?.kind==="global"),d=[i,...s];for(let c=0;c<d.length;c+=w){const a=d.slice(c,c+w);if(!e){for(const b of a)if(await o.get(b,r)!==null)return b;continue}const f=a.map((b,I)=>p`SELECT ${p.raw(String(I))} AS slot FROM ${p.identifier(b)} WHERE ${p.identifier("id")} = ${r}`),u=(await O(e,n,p`${p.join(f,p` UNION ALL `)} ORDER BY slot LIMIT 1`))[0]?.slot;if(u!==void 0)return a[Number(u)]}},y=(o,t,n,e)=>({code:"ID_COLLISION",line:n,message:`_id "${t}" already belongs to table "${o}"`,table:e}),x=async(o,t,n,e,i,r,s)=>{let d;try{d=await v(o,t,n,e,i,r)}catch(c){const{body:a}=k(c,{fallbackCode:"PROBE_FAILED"});return{error:{code:a.code,line:s,message:a.message,table:i}}}return d!==void 0&&d!==i?{error:y(d,r,s,i)}:{existingId:d===i?r:void 0}},g=(o,t,n)=>{const e=o.owners.get(t)??new Set;e.add(n),o.owners.set(t,e)},B=async(o,t,n,e)=>{const i=new Map;let r=[],s=w;const d=async()=>{if(r.length===0)return;const c=await O(o,t,p.join(r,p` UNION ALL `));for(const a of c)g({owners:i},String(a.id),n[Number(a.slot)]);r=[],s=w};try{for(const[c,a]of n.entries())for(let f=0;f<e.length;){const l=e.slice(f,f+s);r.push(p`SELECT ${p.raw(String(c))} AS slot, ${p.identifier("id")} FROM ${p.identifier(a)} WHERE ${p.identifier("id")} IN (${p.join(l.map(u=>p.param(u)),p`, `)})`),f+=l.length,s-=l.length,s===0&&await d()}await d()}catch(c){const{body:a}=k(c,{fallbackCode:"PROBE_FAILED"});return{failure:{code:a.code,message:a.message}}}return{owners:i}},W=(o,t,n,e,i)=>{if("failure"in o)return{error:{...o.failure,line:i,table:n}};const r=o.owners.get(e);if(r?.has(n)===!0)return{existingId:e};const s=t.find(d=>r?.has(d)===!0);return s===void 0?{existingId:void 0}:{error:y(s,e,i,n)}},R=async(o,t,n,e,i)=>{try{if(e!==void 0){const r={...n};return delete r._id,await o.replace(t,e,r,{allowExplicitId:!0}),{kind:"replaced"}}return await o.insert(t,n,{allowExplicitId:!0}),{inserted:t,kind:"inserted"}}catch(r){const{body:s}=k(r,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"});return{error:{code:s.code,line:i,message:s.message,table:t},kind:"error"}}},G=(o,t,n,e)=>{const{doc:i,table:r}=n;if(typeof r!="string"||r.length===0)return{kind:"settled",outcome:{error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:r},kind:"error"}};if(o.tables[r]?.shardMode?.kind!=="global")return{kind:"settled",outcome:{kind:"skip"}};if(!i||typeof i!="object"||Array.isArray(i))return{kind:"settled",outcome:{error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:r},kind:"error"}};let s;try{s=S(i)}catch(c){return{kind:"settled",outcome:{error:{code:"BAD_ROW",line:e,message:c instanceof Error?c.message:String(c),table:r},kind:"error"}}}s=N(o.tables[r],s);const d=j(o,r,s);return d!==void 0?{kind:"settled",outcome:{error:{code:"VALIDATION_ERROR",line:e,message:d,table:r},kind:"error"}}:t?{kind:"settled",outcome:{kind:"checked"}}:{decoded:s,explicitId:typeof s._id=="string"?s._id:void 0,kind:"ready",line:e,table:r}},P=async(o,t,n,e,i,r,s)=>{const{decoded:d,explicitId:c,line:a,table:f}=r;let l;try{l=await v(o,t,n,e,f,c)}catch{return}if(l!==void 0)return g(i,c,l),l!==f?{error:y(l,c,a,f),kind:"error"}:s==="replace"?R(o,f,d,c,a):{kind:"conflict"}},z=async(o,t,n,e,i,r)=>{const{decoded:s,explicitId:d,line:c,table:a}=i;let f={existingId:void 0};if(d!==void 0&&(f=r===void 0?await x(o,t,n,e.exec,a,d,c):W(r,m(t),a,d,c)),"error"in f)return{error:f.error,kind:"error"};const{existingId:l}=f;if(l!==void 0&&e.onConflict!=="replace")return{kind:"conflict"};const u=await R(o,a,s,l,c);if(r===void 0||"failure"in r||e.exec===void 0||d===void 0)return u;if(u.kind==="inserted"||u.kind==="replaced")g(r,d,a);else if(u.kind==="error"&&u.error.code==="CONFLICT"&&l===void 0)return await P(o,t,n,e.exec,r,{...i,explicitId:d},e.onConflict)??u;return u},U=async(o,t,n,e)=>{const i=new Set;for(const r of e)r.kind==="ready"&&r.explicitId!==void 0&&i.add(r.explicitId);if(i.size===0)return{owners:new Map};try{await E(o,t,n)}catch(r){const{body:s}=k(r,{fallbackCode:"PROBE_FAILED"});return{failure:{code:s.code,message:s.message}}}return B(o,n,m(t),[...i])},Z=async(o,t,n,e)=>{const i=[],r={};let s=0,d=0,c=(e.startLine??1)-1;const a=e.rows.map(l=>(c+=1,G(t,e.dryRun===!0,l,l.line??c)));let f;e.exec&&e.dryRun!==!0&&(f=await U(e.exec,t,n,a));for(const l of a){const u=l.kind==="settled"?l.outcome:await z(o,t,n,e,l,f);switch(u.kind){case"conflict":{s+=1;break}case"error":{i.push(u.error);break}case"inserted":{r[u.inserted]=(r[u.inserted]??0)+1;break}case"replaced":{d+=1;break}}}return{conflicts:s,errors:i,inserted:r,replaced:d}};export{Y as exportSqlGlobalRows,Z as importSqlGlobalRows,m as selectGlobalTables};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as G}from"@lunora/shard-engine";import{needsWireEncoding as v,encodeWire as M}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as k}from"./runSqlGlobalTableMigrations-C24sSQdc.mjs";import{q as u,M as T,d as P}from"./sql-exec-CkHeSf_v.mjs";import{s as W,e as Y,a as O}from"./value-codec-C52YW-Do.mjs";const H=50,j=500,X=30,J=200,Q=(t,n,e)=>Math.min(Math.max(t,n),e),g=(t,n,e,a)=>Q(Math.trunc(t!==void 0&&Number.isFinite(t)?t:n),e,a),V=(t,n)=>G(t)||n.name==="sqlite"&&t.startsWith("d1_"),y=t=>t.name==="postgres"?o`current_schema()`:o`DATABASE()`,C=t=>t.filter(n=>Number(n.pk??0)>0).toSorted((n,e)=>Number(n.pk)-Number(e.pk)).map(n=>String(n.name)),p={columns:async(t,n,e)=>(n.name==="sqlite"?await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`):await u(t,n,o`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${y(n)} AND table_name = ${e} ORDER BY ordinal_position`)).map(r=>String(r.name)),foreignKeys:async(t,n,e)=>{let a;return n.name==="sqlite"?a=o`PRAGMA foreign_key_list(${o.identifier(e)})`:n.name==="mysql"?a=o`SELECT column_name AS ${o.identifier("from")}, referenced_table_name AS ${o.identifier("table")} FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = ${e} AND referenced_table_name IS NOT NULL AND referenced_table_schema = DATABASE()`:a=o`SELECT kcu.column_name AS ${o.identifier("from")}, ccu.table_name AS ${o.identifier("table")} FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ${e} AND ccu.table_schema = current_schema()`,(await u(t,n,a)).map(s=>({from:String(s.from),target:String(s.table)}))},primaryKey:async(t,n,e)=>n.name==="sqlite"?C(await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`)):(await u(t,n,o`SELECT kcu.column_name AS name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${y(n)} AND tc.table_name = ${e} ORDER BY kcu.ordinal_position`)).map(r=>String(r.name)),tables:async(t,n)=>(n.name==="sqlite"?await u(t,n,o`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`):await u(t,n,o`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ${y(n)} AND table_type = 'BASE TABLE' ORDER BY table_name`)).map(a=>String(a.name))},z=/password|secret|token|hash|salt|credential/iu,Z=new Map([["apikey",new Set(["key"])],["jwks",new Set(["privatekey"])],["twofactor",new Set(["backupcodes"])],["verification",new Set(["value"])]]),D=t=>t.toLowerCase().replaceAll("_",""),h=(t,n)=>z.test(n)||Z.get(D(t))?.has(D(n))===!0,_=(t,n)=>{const e=t.tables[n];return e?.shardMode?.kind==="global"?e:void 0},L=async(t,n)=>(await p.tables(t,n)).filter(a=>!V(a,n)),I=async(t,n,e,a)=>{if(await k(t,e,n),!(await L(t,n)).includes(a))throw new w("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},R=async(t,n,e,a=o``)=>{const r=await u(t,n,o`SELECT COUNT(*) AS c FROM ${o.identifier(e)}${a}`);return Number(r[0]?.c??0)},q=(t,n,e)=>_(t,n)!==void 0&&e==="_id"?"id":e,B=(t,n,e)=>{const a=_(t,n)?.shape[e];return a===void 0?void 0:Y(a)},x=/^-?\d+$/u,F=(t,n)=>{if(n>T)throw new w("BAD_REQUEST",`the query over ${t} binds ${String(n)} parameters, and a statement takes at most ${String(T)} — remove some filters`)},tt=(t,n,e)=>{if(e)return t instanceof ArrayBuffer?new Uint8Array(t):t;if(n!=="bigint")return O(t);const a=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return O(a!==void 0&&x.test(a)?BigInt(a):t,n)},nt=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new w("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new w("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},U=(t,n,e,a,r)=>{const s=[],i=_(t,e)===void 0&&n.name!=="sqlite";let m=0;for(const c of r??[]){if(nt(c),!a.includes(c.column))throw new w("UNKNOWN_COLUMN",`unknown column: ${c.column}`,{status:404});if(_(t,e)===void 0&&h(e,c.column))throw new w("FORBIDDEN",`cannot filter on a redacted column: ${c.column}`,{status:403});const f=o.identifier(q(t,e,c.column));if(c.value===null||c.value===void 0)s.push(o`${f} IS NULL`);else{const l=tt(c.value,B(t,e,c.column),i);s.push(i&&n.name==="postgres"&&l instanceof Date?o`${f}::timestamptz = ${l}::timestamptz`:o`${f} = ${l}`),m+=1}}return{bound:m,where:s.length>0?o` WHERE ${o.join(s,o` AND `)}`:o``}},et=(t,n,e)=>{const a=_(t,n);if(a)return P(a,e);const r={};for(const[s,i]of Object.entries(e))r[s]=i!=null&&h(n,s)?"•••":i;return r},K=async(t,n,e,a)=>{const r=_(e,a);if(r)return{columns:["_id","_creationTime",...Object.keys(r.shape)],primaryKey:()=>Promise.resolve([])};if(n.name==="sqlite"){const s=await u(t,n,o`PRAGMA table_info(${o.identifier(a)})`);return{columns:s.map(i=>String(i.name)),primaryKey:()=>Promise.resolve(C(s))}}return{columns:await p.columns(t,n,a),primaryKey:()=>p.primaryKey(t,n,a)}},ot=async(t,n,e,a)=>{if(_(e,a))return;const r=await p.foreignKeys(t,n,a);if(r.length===0)return;const s={};for(const i of r){const{from:m,target:c}=i;s[m]??=c}return s},ft=async(t,n,e)=>{await k(t,n,e);const a=await L(t,e);return Promise.all(a.map(async r=>({name:r,rowCount:await R(t,e,r)})))},at=async(t,n,e,a,r)=>{if(_(n,e)!==void 0)return o`${o.identifier("id")}`;const s=await r();return s.length>0?o.join(s.map(i=>o.identifier(i)),o`, `):a.includes("id")?o`${o.identifier("id")}`:t.name==="sqlite"?o.raw("rowid"):o.join(a.map(i=>t.name==="postgres"?o`${o.identifier(i)}::text`:o.identifier(i)),o`, `)},_t=async(t,n,e,a)=>{const{table:r}=a;await I(t,e,n,r);const s=g(a.limit,H,1,j),i=g(a.offset,0,0,Number.MAX_SAFE_INTEGER),{columns:m,primaryKey:c}=await K(t,e,n,r),{bound:f,where:l}=U(n,e,r,m,a.filters);F(r,f);const A=await R(t,e,r,l),d=await at(e,n,r,m,c),S=(await u(t,e,o`SELECT * FROM ${o.identifier(r)}${l} ORDER BY ${d} LIMIT ${o.raw(String(s))} OFFSET ${o.raw(String(i))}`)).map(E=>{const N=et(n,r,E);return v(N)?M(N):N}),b=await ot(t,e,n,r);return b===void 0?{columns:m,rows:S,total:A}:{columns:m,refs:b,rows:S,total:A}},Et=async(t,n,e,a)=>{const{column:r,table:s}=a;await I(t,e,n,s);const{columns:i}=await K(t,e,n,s);if(!i.includes(r))throw new w("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const{bound:m,where:c}=U(n,e,s,i,a.filters);if(F(s,m),_(n,s)===void 0&&h(s,r)){const E=await R(t,e,s,c);return{truncated:!1,values:E===0?[]:[{count:E,value:"•••"}]}}const f=g(a.limit,X,1,J),l=o.identifier(q(n,s,r)),A=await u(t,e,o`SELECT ${l} AS value, COUNT(*) AS count FROM ${o.identifier(s)}${c} GROUP BY ${l} ORDER BY count DESC, ${l} ASC LIMIT ${o.raw(String(f+1))}`),d=A.length>f,$=d?A.slice(0,f):A,S=B(n,s,r)==="bigint",b=$.map(E=>({count:Number(E.count),value:S?W(E.value,"bigint"):E.value}));return{truncated:d,values:v(b)?M(b):b}};export{Et as facetSqlGlobalColumn,ft as listSqlGlobalTables,_t as readSqlGlobalTablePage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{aggregateTableName as Y,rankTableName as X,sortColumnName as O,bigintSqlKey as V}from"@lunora/shard-engine";import{sql as t}from"drizzle-orm";import{b as Q,e as g,B as b,r as z,i as Z,U as J,c as nn}from"./value-codec-C52YW-Do.mjs";import{O as A,t as en,b as d,q as $,c as _,e as m,f as tn,s as on,g as rn}from"./sql-exec-snQLgtvn.mjs";const sn=new Set(["any","null"]),D=(e,n)=>{const i=n.kindOf(e);return i!==void 0&&sn.has(i)||n.nullableOf(e)?!0:i==="union"&&(n.membersOf(e)??[]).some(o=>D(o,n))},S=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?S(n):e},R=e=>D(e,{kindOf:Q,membersOf:n=>S(n)._meta?.members,nullableOf:n=>S(n)._meta?.column?.notNull===!1}),U=(e,n,i=!1)=>n.columnType(g(e),{unique:i||e._meta?.column?.unique===!0}),k=e=>{const n=new Set;for(const i of e.indexes)i.unique===!0&&i.fields.length===1&&n.add(i.fields[0]);return n},an=(e,n,i)=>{if(i.indexKeyPrefix!==void 0)for(const o of n.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(s=>{const a=n.shape[s];return a!==void 0&&i.indexKeyPrefix?.(g(a))!==void 0});if(r.length>0)throw new Error(`${e}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},ln=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!R(e),un=(e,n,i)=>{const o=[],r=k(n);for(const[u,c]of Object.entries(n.shape)){if(!c._meta?.column)continue;const f=ln(c)?" NOT NULL":"";o.push(t`${t.identifier(u)} ${t.raw(`${U(c,i,r.has(u))}${f}`)}`)}const s=[...i.frameworkColumns().map(u=>t`${t.identifier(u.name)} ${t.raw(u.type)}`),t`${t.identifier(A)} ${t.raw(i.companionTypes.integer)}`],a=s.length+o.length,l=i.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,c="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new v("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${A}", the row version every guarded write reads, which caps declared fields at ${String(l-s.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${c}`)}return t.join([...s,...o],t`, `)},x=e=>{if(e.indexKeyPrefix?.("string")===void 0)return t`${m("_creationTime")}, ${m("id")}`},M=async(e,n,i,o)=>{const r=t.join(i.refs.map(a=>t`${a} IS NOT NULL`),t` AND `);if((await $(e,n,t`SELECT ${i.columns} FROM ${t.identifier(i.table)} WHERE ${r} GROUP BY ${i.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0)throw new v("INTERNAL",`unique index "${i.name}" on "${i.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`)},cn=async(e,n,i)=>{if(!i.unique){await _(e,n,i);return}try{await _(e,n,i)}catch(o){throw n.isUniqueViolation(o)&&await M(e,n,i,"cannot be created"),o}},F=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},fn=(e,n)=>{const i=n.unique?t`UNIQUE `:t``;return F(e.render(t`CREATE ${i}INDEX ${t.identifier(n.name)} ON ${t.identifier(n.table)} (${n.columns})`).sql)},dn=(e,n,i)=>{const o=fn(e,i);return o!==void 0&&o!==F(n)},B=async(e,n,i)=>{if(n.name!=="sqlite")return;const r=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i.name} COLLATE NOCASE AND tbl_name = ${i.table} COLLATE NOCASE`))[0]?.sql;typeof r=="string"&&dn(n,r,i)&&(i.unique&&await M(e,n,i,"cannot be re-created with its new column list; the previous index is left in place"),await d(e,n,t`DROP INDEX IF EXISTS ${t.identifier(i.name)}`))},mn=(e,n,i)=>{an(e,n,i);const o=k(n),r=l=>{const u=m(l),c=n.shape[l],f=c&&i.indexKeyPrefix&&c._meta?.column?.unique!==!0&&!o.has(l)?i.indexKeyPrefix(g(c)):void 0;return f===void 0?u:t`${u}(${t.raw(String(f))})`},s=x(i),a=[];for(const l of n.indexes){const u=l.fields.map(E=>r(E)),c=t.join(u,t`, `),f=l.unique??!1;a.push({columns:f||s===void 0?c:t`${c}, ${s}`,kind:"declared",name:`${e}_${l.name}`,refs:u,table:e,unique:f})}s!==void 0&&a.push({columns:s,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[l,u]of en(n)){if(!u.unique)continue;const c=r(l);a.push({columns:c,kind:"unique-column",name:`${e}_unique_${l}`,refs:[c],table:e,unique:!0})}return a},$n=/^\s*create\s+unique\s/iu,T="__lunora_framework_indexes",En=()=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,P=(e,n)=>t`INSERT OR IGNORE INTO ${t.identifier(T)} (name, table_name) VALUES (${e}, ${n})`,w=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),gn=async(e,n,i)=>{if(n.name!=="sqlite"||(await $(e,n,t`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${T} COLLATE NOCASE`)).length>0)return;await d(e,n,En());const r=x(n),s=r===void 0?void 0:`, ${n.render(r).sql})`;for(const a of i){const l=`${w(a)}_`,u=await $(e,n,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const c of u){const f=String(c.name),E=String(c.sql);w(f).startsWith(l)&&w(f)!==w(`${a}__by_creation`)&&($n.test(E)||s!==void 0&&E.trimEnd().endsWith(s))&&await d(e,n,P(f,a))}}},pn=(e,n,i)=>{if(e.name!=="sqlite")return[];const o=new Set(n.map(r=>w(r.name)));return i.filter(r=>!o.has(w(r)))},wn=async(e,n,i,o)=>{if(o.name!=="sqlite")return;const r=await $(e,o,t`SELECT "l"."name" FROM ${t.identifier(T)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const s of pn(o,i,r.map(a=>String(a.name))))await d(e,o,t`DROP INDEX IF EXISTS ${t.identifier(s)}`),await d(e,o,t`DELETE FROM ${t.identifier(T)} WHERE ${t.identifier(T)}."name" = ${s}`)},Tn=async(e,n,i,o)=>{const r=mn(n,i,o);for(const s of r){if(s.kind==="default-order"){await _(e,o,s);continue}s.kind==="declared"&&await B(e,o,s),await cn(e,o,s),o.name==="sqlite"&&await d(e,o,P(s.name,s.table))}await wn(e,n,r,o)},N="__lunora_migration_state",hn=async(e,n)=>{await d(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(N)} (${t.identifier("name")} ${t.raw(n.companionTypes.key)} PRIMARY KEY)`)},_n=async(e,n,i)=>(await $(e,n,t`SELECT ${t.identifier("name")} FROM ${t.identifier(N)} WHERE ${t.identifier("name")} = ${i}`)).length>0,Ln=async(e,n,i,o,r,s)=>{r>0&&s!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${i}" on "${o}": ${String(r)} row(s) ${s} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await d(e,n,t`INSERT INTO ${t.identifier(N)} (${t.identifier("name")}) VALUES (${i})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},yn=100,An=(e,n)=>{const i=[],o=[];for(const r of n.fields){const s=e[r],a=n.convert(s);a!==void 0&&(i.push(t`${m(r)} = ${a}`),o.push(t`${m(r)} = ${s}`))}return{assignments:i,guards:o}},Sn=e=>t.join(e.fields.map(n=>e.probe(n)),t` OR `),j=async(e,n,i,o)=>{if(o.fields.length===0||(await hn(e,i),await _n(e,i,o.marker)))return;const r=Sn(o),s=t.join([m("id"),...o.fields.map(u=>m(u))],t`, `);let a="",l=0;for(;;){const u=await $(e,i,t`SELECT ${s} FROM ${t.identifier(n)} WHERE (${r}) AND ${m("id")} > ${a} ORDER BY ${m("id")} LIMIT ${t.raw(String(yn))}`);if(u.length===0){await Ln(e,i,o.marker,n,l,o.describeUnconvertible);return}const c=[];for(const E of u){const{id:p}=E,{assignments:h,guards:I}=typeof p=="string"?An(E,o):{assignments:[],guards:[]};if(h.length===0){l+=1;continue}c.push(t`UPDATE ${t.identifier(n)} SET ${t.join(h,t`, `)} WHERE ${m("id")} = ${p} AND ${t.join(I,t` AND `)}`)}await rn(e,i,c);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},C=e=>`'${e}%'`,On=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),Rn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&Z(g(n))).map(([n])=>n),K=(e,n)=>({convert:i=>{if(!(typeof i!="string"||i.length===b))try{return V(BigInt(i))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:On(n),marker:`bigint-key:${e}`,probe:i=>t`(${m(i)} IS NOT NULL AND LENGTH(${m(i)}) <> ${b})`}),Nn=async(e,n,i,o)=>j(e,n,o,K(n,i)),G=(e,n)=>({convert:z,fields:Rn(n),marker:`untyped-number-key:${e}`,probe:i=>t`(${m(i)} LIKE ${t.raw(C(J))} AND ${m(i)} NOT LIKE ${t.raw(C(nn))})`}),In=async(e,n,i,o)=>j(e,n,o,G(n,i)),q=new Set,L=(e,n)=>{q.has(e)||(q.add(e),console.warn(`[@lunora/sql-store] ${n}`))},bn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},Cn=(e,n,i)=>i._meta?.column?.unique===!0||e.indexes.some(o=>o.unique===!0&&o.fields.includes(n)),qn=async(e,n,i,o,r,s)=>{if(s.kind==="optional"||R(s))return;const a=Cn(i,r,s),l=a?void 0:bn(s),u=`UPDATE "${n}" SET "${r}" = … WHERE "${r}" IS NULL`;if(l===void 0){const c=a?"is unique, so one default cannot be written to every row":"has no default";L(`backfill:${n}.${r}`,`"${n}.${r}" was added as a required field that ${c}, so rows written before it read NULL. Backfill it with a migration (${u}).`);return}try{await d(e,o,t`UPDATE ${t.identifier(n)} SET ${t.identifier(r)} = ${on(i,r,l)} WHERE ${t.identifier(r)} IS NULL`)}catch(c){L(`backfill:${n}.${r}`,`could not backfill "${n}.${r}" from its default (${c instanceof Error?c.message:String(c)}); rows written before it read NULL. Run ${u}.`)}},vn=(e,n)=>[[A,n.companionTypes.integer],...Object.entries(e.shape).filter(([,i])=>i._meta?.column!==void 0).map(([i,o])=>[i,U(o,n),o])],Dn=async(e,n,i,o)=>{const r=vn(i,o),s="t",a=async l=>{try{return await $(e,o,t`SELECT ${t.join(l.map(u=>tn(s,u)),t`, `)} FROM ${t.identifier(n)} AS ${t.identifier(s)} LIMIT 0`),!0}catch{return!1}};if(!await a(r.map(([l])=>l)))for(const[l,u,c]of r)await a([l])||(await d(e,o,t`ALTER TABLE ${t.identifier(n)} ADD COLUMN ${t.identifier(l)} ${t.raw(u)}`),c!==void 0&&await qn(e,n,i,o,l,c))},Un=(e,n,i)=>{const o=typeof i.charset=="string"?` CHARACTER SET ${i.charset} COLLATE ${String(i.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(i.type)}${o} NULL`},kn=async(e,n,i,o)=>{if(o.name==="sqlite")return;const r=Object.keys(i.shape).filter(s=>{const a=i.shape[s];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&R(a)});if(r.length!==0)try{const s=o.name==="postgres"?t`column_name AS ${t.identifier("name")}`:t`column_name AS ${t.identifier("name")}, column_type AS ${t.identifier("type")}, character_set_name AS ${t.identifier("charset")}, collation_name AS ${t.identifier("collation")}`,a=o.name==="postgres"?t`table_schema = ANY (current_schemas(false))`:t`table_schema = DATABASE()`,l=await $(e,o,t`SELECT ${s} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${t.join(r.map(u=>t`${u}`),t`, `)})`);for(const u of l){const c=String(u.name);if(o.name==="postgres"){await d(e,o,t`ALTER TABLE ${t.identifier(n)} ALTER COLUMN ${t.identifier(c)} DROP NOT NULL`);continue}L(`${n}.${c}`,`"${n}"."${c}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${Un(n,c,u)};`)}}catch(s){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${r.join(", ")}): ${s instanceof Error?s.message:String(s)}. Writing null to them fails until the constraint is dropped by hand.`)}},xn=async(e,n,i,o)=>{const r=un(n,i,o);await d(e,o,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${r})`),await Dn(e,n,i,o),await kn(e,n,i,o),await Tn(e,n,i,o),await Nn(e,n,i,o),await In(e,n,i,o)},Yn=(e,n)=>[K(e,n),G(e,n)].filter(i=>i.fields.length>0),Xn=async(e,n,i,o)=>{let r=!1;for(const[s,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(s)||(r||(r=!0,await gn(e,i,Object.entries(n.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await xn(e,s,a,i))},H=e=>e.shardMode===void 0||e.shardMode.kind==="global",Vn=async(e,n,i)=>{const{integer:o,key:r,real:s}=i.companionTypes;for(const[a,l]of Object.entries(n.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!H(l)))for(const c of u){const f=Y(a,c.name);await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(f)} (${t.identifier("__key__")} ${t.raw(r)} PRIMARY KEY, ${t.identifier("__value__")} ${t.raw(s)}, ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0)`),i.name==="sqlite"&&((await $(e,i,t`PRAGMA table_info(${t.identifier(f)})`)).some(p=>p.name==="__count__")||await d(e,i,t`ALTER TABLE ${t.identifier(f)} ADD COLUMN ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0`))}}},y=(e,n,i,o)=>{const r=e.name==="mysql"&&o?t`${t.identifier(n)}(191)`:t`${t.identifier(n)}`;return t`${r} ${t.raw(i)}`},Mn=(e,n,i)=>{const o=[y(e,"__partition__","ASC",!0)];for(const[r,s]of n.sortBy.entries()){const a=i.shape[s.field],l=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;o.push(y(e,O(r),s.direction==="desc"?"DESC":"ASC",l))}return o.push(y(e,"__id__","ASC",!0)),o},Fn=(e,n,i)=>n.sortBy.map((o,r)=>{const s=i.shape[o.field],a=e.columnType(s?g(s):void 0);return t`${t.identifier(O(r))} ${t.raw(a)}`}),Bn=/__sort_k\d+__/gu,Pn=async(e,n,i,o)=>{if(n.name!=="sqlite")return;const s=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${i} COLLATE NOCASE`))[0]?.sql;if(typeof s!="string")return;const a=s.match(Bn)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await d(e,n,t`DROP TABLE ${t.identifier(i)}`)},Qn=async(e,n,i)=>{const{key:o}=i.companionTypes;for(const[r,s]of Object.entries(n.tables)){const a=s.rankIndexes;if(!(!a||a.length===0||!H(s)))for(const l of a){const u=X(r,l.name),c=Fn(i,l,s);await Pn(e,i,u,l.sortBy.map((I,W)=>O(W)));const f=c.length>0?t`, ${t.join(c,t`, `)}`:t``;await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(u)} (${t.identifier("__id__")} ${t.raw(o)} PRIMARY KEY, ${t.identifier("__partition__")} ${t.raw(o)} NOT NULL${f})`);const E=Mn(i,l,s),p=`${r}__rank_${l.name}__btree`,h={columns:t.join(E,t`, `),name:p,refs:[],table:u,unique:!1};await B(e,i,h),await _(e,i,h)}}};export{T as INDEX_LEDGER_TABLE,N as MIGRATION_STATE_TABLE,fn as declaredIndexColumnList,w as foldIdentifier,un as globalTableColumnsDdl,mn as globalTableIndexSpecs,F as indexColumnList,En as indexLedgerDdl,dn as indexShapeChanged,Yn as legacyRewrites,Sn as legacyRowPredicate,xn as provisionGlobalTable,Xn as provisionGlobalTablesSequentially,P as recordIndexStatement,Vn as runSqlAggregateMigrations,Qn as runSqlRankMigrations,pn as undeclaredFrameworkIndexes,vn as wantedGlobalColumns};
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{aggregateTableName as Y,rankTableName as X,sortColumnName as O,bigintSqlKey as V}from"@lunora/shard-engine";import{sql as t}from"drizzle-orm";import{b as Q,e as g,B as b,r as z,i as Z,U as J,c as nn}from"./value-codec-C52YW-Do.mjs";import{O as A,t as en,b as d,q as $,c as _,e as m,f as tn,s as on,g as rn}from"./sql-exec-CkHeSf_v.mjs";const sn=new Set(["any","null"]),D=(e,n)=>{const i=n.kindOf(e);return i!==void 0&&sn.has(i)||n.nullableOf(e)?!0:i==="union"&&(n.membersOf(e)??[]).some(o=>D(o,n))},S=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?S(n):e},R=e=>D(e,{kindOf:Q,membersOf:n=>S(n)._meta?.members,nullableOf:n=>S(n)._meta?.column?.notNull===!1}),U=(e,n,i=!1)=>n.columnType(g(e),{unique:i||e._meta?.column?.unique===!0}),k=e=>{const n=new Set;for(const i of e.indexes)i.unique===!0&&i.fields.length===1&&n.add(i.fields[0]);return n},an=(e,n,i)=>{if(i.indexKeyPrefix!==void 0)for(const o of n.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(s=>{const a=n.shape[s];return a!==void 0&&i.indexKeyPrefix?.(g(a))!==void 0});if(r.length>0)throw new Error(`${e}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},ln=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!R(e),un=(e,n,i)=>{const o=[],r=k(n);for(const[u,c]of Object.entries(n.shape)){if(!c._meta?.column)continue;const f=ln(c)?" NOT NULL":"";o.push(t`${t.identifier(u)} ${t.raw(`${U(c,i,r.has(u))}${f}`)}`)}const s=[...i.frameworkColumns().map(u=>t`${t.identifier(u.name)} ${t.raw(u.type)}`),t`${t.identifier(A)} ${t.raw(i.companionTypes.integer)}`],a=s.length+o.length,l=i.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,c="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new v("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${A}", the row version every guarded write reads, which caps declared fields at ${String(l-s.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${c}`)}return t.join([...s,...o],t`, `)},x=e=>{if(e.indexKeyPrefix?.("string")===void 0)return t`${m("_creationTime")}, ${m("id")}`},M=async(e,n,i,o)=>{const r=t.join(i.refs.map(a=>t`${a} IS NOT NULL`),t` AND `);if((await $(e,n,t`SELECT ${i.columns} FROM ${t.identifier(i.table)} WHERE ${r} GROUP BY ${i.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0)throw new v("INTERNAL",`unique index "${i.name}" on "${i.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`)},cn=async(e,n,i)=>{if(!i.unique){await _(e,n,i);return}try{await _(e,n,i)}catch(o){throw n.isUniqueViolation(o)&&await M(e,n,i,"cannot be created"),o}},F=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},fn=(e,n)=>{const i=n.unique?t`UNIQUE `:t``;return F(e.render(t`CREATE ${i}INDEX ${t.identifier(n.name)} ON ${t.identifier(n.table)} (${n.columns})`).sql)},dn=(e,n,i)=>{const o=fn(e,i);return o!==void 0&&o!==F(n)},B=async(e,n,i)=>{if(n.name!=="sqlite")return;const r=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i.name} COLLATE NOCASE AND tbl_name = ${i.table} COLLATE NOCASE`))[0]?.sql;typeof r=="string"&&dn(n,r,i)&&(i.unique&&await M(e,n,i,"cannot be re-created with its new column list; the previous index is left in place"),await d(e,n,t`DROP INDEX IF EXISTS ${t.identifier(i.name)}`))},mn=(e,n,i)=>{an(e,n,i);const o=k(n),r=l=>{const u=m(l),c=n.shape[l],f=c&&i.indexKeyPrefix&&c._meta?.column?.unique!==!0&&!o.has(l)?i.indexKeyPrefix(g(c)):void 0;return f===void 0?u:t`${u}(${t.raw(String(f))})`},s=x(i),a=[];for(const l of n.indexes){const u=l.fields.map(E=>r(E)),c=t.join(u,t`, `),f=l.unique??!1;a.push({columns:f||s===void 0?c:t`${c}, ${s}`,kind:"declared",name:`${e}_${l.name}`,refs:u,table:e,unique:f})}s!==void 0&&a.push({columns:s,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[l,u]of en(n)){if(!u.unique)continue;const c=r(l);a.push({columns:c,kind:"unique-column",name:`${e}_unique_${l}`,refs:[c],table:e,unique:!0})}return a},$n=/^\s*create\s+unique\s/iu,T="__lunora_framework_indexes",En=()=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,P=(e,n)=>t`INSERT OR IGNORE INTO ${t.identifier(T)} (name, table_name) VALUES (${e}, ${n})`,w=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),gn=async(e,n,i)=>{if(n.name!=="sqlite"||(await $(e,n,t`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${T} COLLATE NOCASE`)).length>0)return;await d(e,n,En());const r=x(n),s=r===void 0?void 0:`, ${n.render(r).sql})`;for(const a of i){const l=`${w(a)}_`,u=await $(e,n,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const c of u){const f=String(c.name),E=String(c.sql);w(f).startsWith(l)&&w(f)!==w(`${a}__by_creation`)&&($n.test(E)||s!==void 0&&E.trimEnd().endsWith(s))&&await d(e,n,P(f,a))}}},pn=(e,n,i)=>{if(e.name!=="sqlite")return[];const o=new Set(n.map(r=>w(r.name)));return i.filter(r=>!o.has(w(r)))},wn=async(e,n,i,o)=>{if(o.name!=="sqlite")return;const r=await $(e,o,t`SELECT "l"."name" FROM ${t.identifier(T)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const s of pn(o,i,r.map(a=>String(a.name))))await d(e,o,t`DROP INDEX IF EXISTS ${t.identifier(s)}`),await d(e,o,t`DELETE FROM ${t.identifier(T)} WHERE ${t.identifier(T)}."name" = ${s}`)},Tn=async(e,n,i,o)=>{const r=mn(n,i,o);for(const s of r){if(s.kind==="default-order"){await _(e,o,s);continue}s.kind==="declared"&&await B(e,o,s),await cn(e,o,s),o.name==="sqlite"&&await d(e,o,P(s.name,s.table))}await wn(e,n,r,o)},N="__lunora_migration_state",hn=async(e,n)=>{await d(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(N)} (${t.identifier("name")} ${t.raw(n.companionTypes.key)} PRIMARY KEY)`)},_n=async(e,n,i)=>(await $(e,n,t`SELECT ${t.identifier("name")} FROM ${t.identifier(N)} WHERE ${t.identifier("name")} = ${i}`)).length>0,Ln=async(e,n,i,o,r,s)=>{r>0&&s!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${i}" on "${o}": ${String(r)} row(s) ${s} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await d(e,n,t`INSERT INTO ${t.identifier(N)} (${t.identifier("name")}) VALUES (${i})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},yn=100,An=(e,n)=>{const i=[],o=[];for(const r of n.fields){const s=e[r],a=n.convert(s);a!==void 0&&(i.push(t`${m(r)} = ${a}`),o.push(t`${m(r)} = ${s}`))}return{assignments:i,guards:o}},Sn=e=>t.join(e.fields.map(n=>e.probe(n)),t` OR `),j=async(e,n,i,o)=>{if(o.fields.length===0||(await hn(e,i),await _n(e,i,o.marker)))return;const r=Sn(o),s=t.join([m("id"),...o.fields.map(u=>m(u))],t`, `);let a="",l=0;for(;;){const u=await $(e,i,t`SELECT ${s} FROM ${t.identifier(n)} WHERE (${r}) AND ${m("id")} > ${a} ORDER BY ${m("id")} LIMIT ${t.raw(String(yn))}`);if(u.length===0){await Ln(e,i,o.marker,n,l,o.describeUnconvertible);return}const c=[];for(const E of u){const{id:p}=E,{assignments:h,guards:I}=typeof p=="string"?An(E,o):{assignments:[],guards:[]};if(h.length===0){l+=1;continue}c.push(t`UPDATE ${t.identifier(n)} SET ${t.join(h,t`, `)} WHERE ${m("id")} = ${p} AND ${t.join(I,t` AND `)}`)}await rn(e,i,c);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},C=e=>`'${e}%'`,On=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),Rn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&Z(g(n))).map(([n])=>n),K=(e,n)=>({convert:i=>{if(!(typeof i!="string"||i.length===b))try{return V(BigInt(i))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:On(n),marker:`bigint-key:${e}`,probe:i=>t`(${m(i)} IS NOT NULL AND LENGTH(${m(i)}) <> ${b})`}),Nn=async(e,n,i,o)=>j(e,n,o,K(n,i)),G=(e,n)=>({convert:z,fields:Rn(n),marker:`untyped-number-key:${e}`,probe:i=>t`(${m(i)} LIKE ${t.raw(C(J))} AND ${m(i)} NOT LIKE ${t.raw(C(nn))})`}),In=async(e,n,i,o)=>j(e,n,o,G(n,i)),q=new Set,L=(e,n)=>{q.has(e)||(q.add(e),console.warn(`[@lunora/sql-store] ${n}`))},bn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},Cn=(e,n,i)=>i._meta?.column?.unique===!0||e.indexes.some(o=>o.unique===!0&&o.fields.includes(n)),qn=async(e,n,i,o,r,s)=>{if(s.kind==="optional"||R(s))return;const a=Cn(i,r,s),l=a?void 0:bn(s),u=`UPDATE "${n}" SET "${r}" = … WHERE "${r}" IS NULL`;if(l===void 0){const c=a?"is unique, so one default cannot be written to every row":"has no default";L(`backfill:${n}.${r}`,`"${n}.${r}" was added as a required field that ${c}, so rows written before it read NULL. Backfill it with a migration (${u}).`);return}try{await d(e,o,t`UPDATE ${t.identifier(n)} SET ${t.identifier(r)} = ${on(i,r,l)} WHERE ${t.identifier(r)} IS NULL`)}catch(c){L(`backfill:${n}.${r}`,`could not backfill "${n}.${r}" from its default (${c instanceof Error?c.message:String(c)}); rows written before it read NULL. Run ${u}.`)}},vn=(e,n)=>[[A,n.companionTypes.integer],...Object.entries(e.shape).filter(([,i])=>i._meta?.column!==void 0).map(([i,o])=>[i,U(o,n),o])],Dn=async(e,n,i,o)=>{const r=vn(i,o),s="t",a=async l=>{try{return await $(e,o,t`SELECT ${t.join(l.map(u=>tn(s,u)),t`, `)} FROM ${t.identifier(n)} AS ${t.identifier(s)} LIMIT 0`),!0}catch{return!1}};if(!await a(r.map(([l])=>l)))for(const[l,u,c]of r)await a([l])||(await d(e,o,t`ALTER TABLE ${t.identifier(n)} ADD COLUMN ${t.identifier(l)} ${t.raw(u)}`),c!==void 0&&await qn(e,n,i,o,l,c))},Un=(e,n,i)=>{const o=typeof i.charset=="string"?` CHARACTER SET ${i.charset} COLLATE ${String(i.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(i.type)}${o} NULL`},kn=async(e,n,i,o)=>{if(o.name==="sqlite")return;const r=Object.keys(i.shape).filter(s=>{const a=i.shape[s];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&R(a)});if(r.length!==0)try{const s=o.name==="postgres"?t`column_name AS ${t.identifier("name")}`:t`column_name AS ${t.identifier("name")}, column_type AS ${t.identifier("type")}, character_set_name AS ${t.identifier("charset")}, collation_name AS ${t.identifier("collation")}`,a=o.name==="postgres"?t`table_schema = ANY (current_schemas(false))`:t`table_schema = DATABASE()`,l=await $(e,o,t`SELECT ${s} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${t.join(r.map(u=>t`${u}`),t`, `)})`);for(const u of l){const c=String(u.name);if(o.name==="postgres"){await d(e,o,t`ALTER TABLE ${t.identifier(n)} ALTER COLUMN ${t.identifier(c)} DROP NOT NULL`);continue}L(`${n}.${c}`,`"${n}"."${c}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${Un(n,c,u)};`)}}catch(s){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${r.join(", ")}): ${s instanceof Error?s.message:String(s)}. Writing null to them fails until the constraint is dropped by hand.`)}},xn=async(e,n,i,o)=>{const r=un(n,i,o);await d(e,o,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${r})`),await Dn(e,n,i,o),await kn(e,n,i,o),await Tn(e,n,i,o),await Nn(e,n,i,o),await In(e,n,i,o)},Yn=(e,n)=>[K(e,n),G(e,n)].filter(i=>i.fields.length>0),Xn=async(e,n,i,o)=>{let r=!1;for(const[s,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(s)||(r||(r=!0,await gn(e,i,Object.entries(n.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await xn(e,s,a,i))},H=e=>e.shardMode===void 0||e.shardMode.kind==="global",Vn=async(e,n,i)=>{const{integer:o,key:r,real:s}=i.companionTypes;for(const[a,l]of Object.entries(n.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!H(l)))for(const c of u){const f=Y(a,c.name);await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(f)} (${t.identifier("__key__")} ${t.raw(r)} PRIMARY KEY, ${t.identifier("__value__")} ${t.raw(s)}, ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0)`),i.name==="sqlite"&&((await $(e,i,t`PRAGMA table_info(${t.identifier(f)})`)).some(p=>p.name==="__count__")||await d(e,i,t`ALTER TABLE ${t.identifier(f)} ADD COLUMN ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0`))}}},y=(e,n,i,o)=>{const r=e.name==="mysql"&&o?t`${t.identifier(n)}(191)`:t`${t.identifier(n)}`;return t`${r} ${t.raw(i)}`},Mn=(e,n,i)=>{const o=[y(e,"__partition__","ASC",!0)];for(const[r,s]of n.sortBy.entries()){const a=i.shape[s.field],l=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;o.push(y(e,O(r),s.direction==="desc"?"DESC":"ASC",l))}return o.push(y(e,"__id__","ASC",!0)),o},Fn=(e,n,i)=>n.sortBy.map((o,r)=>{const s=i.shape[o.field],a=e.columnType(s?g(s):void 0);return t`${t.identifier(O(r))} ${t.raw(a)}`}),Bn=/__sort_k\d+__/gu,Pn=async(e,n,i,o)=>{if(n.name!=="sqlite")return;const s=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${i} COLLATE NOCASE`))[0]?.sql;if(typeof s!="string")return;const a=s.match(Bn)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await d(e,n,t`DROP TABLE ${t.identifier(i)}`)},Qn=async(e,n,i)=>{const{key:o}=i.companionTypes;for(const[r,s]of Object.entries(n.tables)){const a=s.rankIndexes;if(!(!a||a.length===0||!H(s)))for(const l of a){const u=X(r,l.name),c=Fn(i,l,s);await Pn(e,i,u,l.sortBy.map((I,W)=>O(W)));const f=c.length>0?t`, ${t.join(c,t`, `)}`:t``;await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(u)} (${t.identifier("__id__")} ${t.raw(o)} PRIMARY KEY, ${t.identifier("__partition__")} ${t.raw(o)} NOT NULL${f})`);const E=Mn(i,l,s),p=`${r}__rank_${l.name}__btree`,h={columns:t.join(E,t`, `),name:p,refs:[],table:u,unique:!1};await B(e,i,h),await _(e,i,h)}}};export{T as INDEX_LEDGER_TABLE,N as MIGRATION_STATE_TABLE,fn as declaredIndexColumnList,w as foldIdentifier,un as globalTableColumnsDdl,mn as globalTableIndexSpecs,F as indexColumnList,En as indexLedgerDdl,dn as indexShapeChanged,Yn as legacyRewrites,Sn as legacyRowPredicate,xn as provisionGlobalTable,Xn as provisionGlobalTablesSequentially,P as recordIndexStatement,Vn as runSqlAggregateMigrations,Qn as runSqlRankMigrations,pn as undeclaredFrameworkIndexes,vn as wantedGlobalColumns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as a}from"drizzle-orm";import{provisionGlobalTablesSequentially as m,foldIdentifier as c,globalTableColumnsDdl as A,globalTableIndexSpecs as L,legacyRewrites as O,indexLedgerDdl as R,wantedGlobalColumns as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-
|
|
1
|
+
import{sql as a}from"drizzle-orm";import{provisionGlobalTablesSequentially as m,foldIdentifier as c,globalTableColumnsDdl as A,globalTableIndexSpecs as L,legacyRewrites as O,indexLedgerDdl as R,wantedGlobalColumns as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-Bje8kPUQ.mjs";import{a as q,q as g}from"./sql-exec-CkHeSf_v.mjs";const v=50,h=new Map([["'","'"],["[","]"],["`","`"],['"','"']]),N=/^[\w$]+/u,b=(e,s)=>{const n=h.get(e[s]);let t=s+1;for(;t<e.length;)if(e[t]!==n)t+=1;else if(n!=="]"&&e[t+1]===n)t+=2;else return t+1;return t},_=e=>{const s=e.trim(),n=h.get(s[0]??"");if(n===void 0)return N.exec(s)?.[0];const t=b(s,0),r=s.slice(1,s[t-1]===n?t-1:t);return n==="]"?r:r.replaceAll(`${n}${n}`,n)},B=e=>{const s=new Set,n=i=>{const d=_(i);d!==void 0&&s.add(d)};let t=0,r=0,o=0;for(;o<e.length;){const i=e[o];if(h.has(i)){o=b(e,o);continue}if(i==="(")t+=1,r=t===1?o+1:r;else if(i===")"){if(t-=1,t===0)return n(e.slice(r,o)),s}else i===","&&t===1&&(n(e.slice(r,o)),r=o+1);o+=1}return s},F=async(e,s,n)=>{const t=new Set,r=new Map,o=n.has(c(T)),i=[];if(n.has(c(E))&&i.push(a`SELECT 'marker' AS kind, name, NULL AS owner FROM ${a.identifier(E)}`),o&&i.push(a`SELECT 'index' AS kind, "l"."name" AS name, "l"."table_name" AS owner FROM ${a.identifier(T)} AS "l"`),i.length===0)return{hasLedger:o,markers:t,owned:r};for(const d of await g(e,s,a.join(i,a` UNION ALL `)))if(d.kind==="marker")t.add(String(d.name));else{const f=c(String(d.owner));r.set(f,[...r.get(f)??[],String(d.name)])}return{hasLedger:o,markers:t,owned:r}},D=async(e,s)=>{try{const n=await g(e,s,a`SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index')`),t=new Set,r=new Map,o=new Map;for(const l of n){const u=String(l.name);if(u.startsWith("sqlite_"))continue;const S=typeof l.sql=="string"?l.sql:void 0;l.type==="table"?(t.add(c(u)),r.set(c(u),new Set([...S===void 0?[]:B(S)].map(I=>c(I))))):o.set(c(u),S)}const{hasLedger:i,markers:d,owned:f}=await F(e,s,t);return{columns:r,hasLedger:i,indexes:o,markers:d,owned:f,tables:t}}catch{return}},w=e=>e.kind==="default-order"?[]:[M(e.name,e.table)],p=e=>{const s=e.unique?a`UNIQUE `:a``;return a`CREATE ${s}INDEX IF NOT EXISTS ${a.identifier(e.name)} ON ${a.identifier(e.table)} (${e.columns})`},x=(e,s,n)=>n.length===0?[]:[a`CREATE TABLE IF NOT EXISTS ${a.identifier(E)} (${a.identifier("name")} ${a.raw(e.companionTypes.key)} PRIMARY KEY)`,...n.map(t=>a`INSERT OR IGNORE INTO ${a.identifier(E)} (${a.identifier("name")}) SELECT ${t.marker} WHERE NOT EXISTS (SELECT 1 FROM ${a.identifier(s)} WHERE ${C(t)})`)],G=(e,s,n,t)=>{const r=A(e,s,n),o=L(e,s,n),i=O(e,s);if(!t.tables.has(c(e)))return[...t.hasLedger?[]:[R()],a`CREATE TABLE IF NOT EXISTS ${a.identifier(e)} (${r})`,...o.flatMap(l=>[p(l),...w(l)]),...x(n,e,i)];const d=t.columns.get(c(e))??new Set;if(k(s,n).some(([l])=>!d.has(c(l)))||i.some(l=>!t.markers.has(l.marker))||y(n,o,t.owned.get(c(e))??[]).length>0)return;const f=[];for(const l of o){if(!t.indexes.has(c(l.name))){f.push(p(l),...w(l));continue}const u=t.indexes.get(c(l.name));if(l.kind==="declared"&&typeof u=="string"&&$(n,u,l))return}return f},X=e=>{const s=[];let n=[],t=0;for(const r of e)n.length>0&&t+r.statements.length>v&&(s.push(n),n=[],t=0),n.push(r),t+=r.statements.length;return n.length>0&&s.push(n),s},U=(e,s)=>!s.hasLedger&&Object.entries(e.tables).some(([n,t])=>t.shardMode?.kind==="global"&&s.tables.has(c(n))),Q=async(e,s,n)=>{if(!e.batch||n.name!=="sqlite"){await m(e,s,n);return}const t=await D(e,n);if(t===void 0){await m(e,s,n);return}if(U(s,t)){await m(e,s,n);return}const r=[],o=new Set;for(const[i,d]of Object.entries(s.tables)){if(d.shardMode?.kind!=="global")continue;const f=G(i,d,n,t);f===void 0?o.add(i):f.length>0&&r.push({statements:f,table:i})}for(const i of X(r))try{await q(e,n,i.flatMap(d=>d.statements))}catch{for(const d of i)o.add(d.table)}await m(e,s,n,o)};export{B as columnNamesOfCreateTable,Q as runSqlGlobalTableMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{needsWireEncoding as J}from"@lunora/wire";import{sql as e,SQL as v}from"drizzle-orm";import{a as A,s as x,e as U}from"./value-codec-C52YW-Do.mjs";const W=t=>{if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===null||n===Object.prototype},p=4;class T extends Error{}const S=t=>t.includes("."),w=t=>{const n=t.split(".");if(n.length>p||n.includes(""))throw new T(`field path "${t}" must have 1 to ${String(p)} non-empty segments`);return n},it=(t,n)=>{if(!S(n))return t[n];let s=t;for(const r of w(n)){if(!W(s)||!Object.hasOwn(s,r))return;s=s[r]}return s},B={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"},X=/^[A-Za-z_$][\w$]*$/u,R=t=>X.test(t)?t:`"${t.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,at="_version",ct=100,I=t=>t==="_id"||t==="id"?"id":t,$=t=>e`${e.identifier(I(t))}`,C=t=>{try{return w(t)}catch(n){throw n instanceof T?new g("VALIDATION_ERROR",n.message):n}},q=new WeakMap,lt=t=>q.get(t),b=(t,n)=>{let s=e`${t}::jsonb`;for(const r of n)s=e`${s} -> ${r}::text`;return e`NULLIF(${s}, 'null'::jsonb)`},k=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} END`,K=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} #>> '{}' END`,L=(t,n)=>{const s=`$${n.map(r=>`.${R(r)}`).join("")}`;return e`NULLIF(JSON_EXTRACT(${t}, ${s}), CAST('null' AS JSON))`},V=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN ${L(t,n)} END`,z=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN JSON_UNQUOTE(${L(t,n)}) END`,ut=(t,n)=>t==="postgres"?e`(${n})::jsonb #>> '{}'`:e`JSON_UNQUOTE(${n})`,y=(t,n)=>{const[s="",...r]=C(n),o=$(s);return e`CASE WHEN json_valid(${o}) THEN ${e.raw(t)}(${o}, ${`$.${r.map(i=>R(i)).join(".")}`}) END`},G=(t,n)=>{if(!S(n))return $(n);if(t.name==="sqlite")return y("json_extract",n);const[s="",...r]=C(n),o=$(s),i=t.name==="postgres",a=i?k(o,r):V(o,r);return q.set(a,i?K(o,r):z(o,r)),a},D=new WeakMap,M=t=>e`CAST(CAST(${t} AS text) AS jsonb)`,dt=(t,n,s)=>{if(t.name==="sqlite")return e`NULLIF(${y("json_type",n)}, 'null') IN (${e.raw(B[s])})`;const r=G(t,n);if(t.name==="postgres")return e`jsonb_typeof(${r}) = ${e.raw(`'${s}'`)}`;const o={boolean:"'BOOLEAN'",number:"'INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL'",string:"'STRING'"}[s];return e`JSON_TYPE(${r}) IN (${e.raw(o)})`},Q=(t,n)=>{if(n===void 0)return n;if(typeof n=="bigint"||J(n))return t==="postgres"?e`CAST(NULL AS jsonb)`:e`CAST(NULL AS JSON)`;const s=JSON.stringify(n),r=t==="postgres"?e`${M(s)}`:e`CAST(${s} AS JSON)`;return D.set(r,s),r},ft=(t,n,s,r)=>{const o=[];let i=!1;for(const u of s){if(u===void 0)throw new g("BAD_REQUEST","an `in` list holds an undefined value");const d=u instanceof v?D.get(u):void 0;d===void 0?i=!0:o.push(d)}if(o.length===0||r&&i)return e`1 = 0`;const a=`[${o.join(",")}]`,c=t==="postgres"?e`SELECT e.v FROM jsonb_array_elements(${M(a)}) AS e(v)`:e`SELECT jt.v FROM JSON_TABLE(${a}, '$[*]' COLUMNS (v JSON PATH '$')) AS jt`;return r?e`${n} NOT IN (${c})`:e`${n} IN (${c})`},Et=(t,n,s,r)=>t.name==="sqlite"||!S(n)||s===null?r(s):Q(t.name,s),$t=(t,n)=>e`${e.identifier(t)}.${e.identifier(I(n))}`,mt=t=>{const n=[];for(const[s,r]of Object.entries(t.shape)){const o=r._meta?.column;o&&n.push([s,o])}return n},f=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.all(o,r)},l=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.run(o,r)},St=(t,n,s)=>t==="postgres"?e`${n} IS NOT DISTINCT FROM ${s}`:t==="mysql"?e`${n} <=> ${s}`:e`${n} IS ${s}`,Nt={sql:t=>e`COALESCE(${t}, 0) + 1`,value:t=>(t==null?0:Number(t))+1},pt=async(t,n,s)=>{if(s.length!==0){if(!t.batch){for(const r of s)await l(t,n,r);return}await t.batch(s.map(r=>n.render(r)))}},_t=async(t,n,s)=>{if(t.batch&&n.name==="sqlite"){await t.batch(s.map(r=>n.render(r)));return}for(const r of s)await l(t,n,r)},Ot=async(t,n,s)=>{const r=s.unique?e`UNIQUE `:e``,o=s.concurrently===!0&&n.name==="postgres"?e`CONCURRENTLY `:e``;if(n.name==="mysql"){try{await l(t,n,e`CREATE ${r}INDEX ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)}catch(i){const a=i;if(a.errno!==1061&&a.code!=="ER_DUP_KEYNAME"&&a.code!==1061)throw i}return}await l(t,n,e`CREATE ${r}INDEX ${o}IF NOT EXISTS ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)},j=(t,n)=>e`(SELECT ${e.identifier("c")}.oid FROM pg_index ${e.identifier("i")} JOIN pg_class ${e.identifier("c")} ON ${e.identifier("c")}.oid = ${e.identifier("i")}.indexrelid WHERE ${e.identifier("i")}.indrelid = to_regclass(quote_ident(${t})) AND ${e.identifier("c")}.relname = ${n}::name)`,ht=async(t,n,s,r)=>{if(n.name==="postgres"){const[o]=await f(t,n,e`SELECT quote_ident(${e.identifier("n")}.nspname) || '.' || quote_ident(${e.identifier("c")}.relname) AS ${e.identifier("qualified")} FROM pg_class ${e.identifier("c")} JOIN pg_namespace ${e.identifier("n")} ON ${e.identifier("n")}.oid = ${e.identifier("c")}.relnamespace WHERE ${e.identifier("c")}.oid = ${j(s,r)}`),i=o?.qualified;typeof i=="string"&&await l(t,n,e`DROP INDEX IF EXISTS ${e.raw(i)}`);return}if(n.name!=="mysql"){await l(t,n,e`DROP INDEX IF EXISTS ${e.identifier(r)}`);return}try{await l(t,n,e`DROP INDEX ${e.identifier(r)} ON ${e.identifier(s)}`)}catch(o){const i=o;if(i.errno!==1091&&i.code!=="ER_CANT_DROP_FIELD_OR_KEY"&&i.code!==1091)throw o}},gt=async(t,n,s,r)=>{switch(n.name){case"mysql":return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s} AND index_name = ${r} LIMIT 1`)).length>0?"valid":"absent";case"postgres":{const o=await f(t,n,e`SELECT indisvalid FROM pg_index WHERE indexrelid = ${j(s,r)}`);return o.length===0?"absent":o[0]?.indisvalid===!0?"valid":"invalid"}default:return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM sqlite_master WHERE type = 'index' AND name = ${r}`)).length>0?"valid":"absent"}},At=A,m=t=>{if(t===void 0)return!1;if(t._meta?.column?.notNull===!1)return!0;switch(t.kind){case"any":case"null":return!0;case"literal":return t._meta?.value===null;case"optional":return m(t._meta?.inner);case"union":return t._meta?.members?.some(n=>m(n))===!0;default:return!1}},Y=t=>t.kind==="optional"&&!m(t),_=new WeakMap,P=t=>{let n=_.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([s,r])=>[s,U(r),Y(r)]),_.set(t,n)),n},O=new WeakMap,Z=(t,n)=>{let s=O.get(t);return s===void 0&&(s=new Map(P(t).map(([r,o])=>[r,o])),O.set(t,s)),s.get(n)},Tt=(t,n,s)=>A(s,Z(t,n)),tt=(t,n)=>{const s={};for(const[r,o,i]of P(t)){const a=n[r];a===void 0||i&&a===null||(s[r]=x(a,o))}return s._id=n.id,s._creationTime=n._creationTime,s},F=(t,n)=>n?tt(t,n):null,wt=(t,n)=>{const s=[];for(const r of n){const o=F(t,r);o&&s.push(o)}return s},h=500,nt=(t,n,s,r,o)=>{const i=e`${e.identifier(s)}.${e.identifier("id")}`,a=r===void 0?e``:e` WHERE ${i} > ${r}`;return f(t,n,e`SELECT * FROM ${e.identifier(s)}${a} ORDER BY ${i} ASC LIMIT ${e.raw(String(o))}`)},Rt=async(t,n,s,r,o,i={})=>{let a=i.after,c=i.limit,u=!0;for(;u&&(c===void 0||c>0);){const d=c===void 0?h:Math.min(h,c),E=await nt(t,n,r,a,d);for(const H of E){const N=F(s,H);N&&await o(N)}a=E.at(-1)?.id,u=E.length===d,c=c===void 0?void 0:c-E.length}};export{h as B,ct as M,at as O,_t as a,l as b,Ot as c,tt as d,$ as e,$t as f,pt as g,ut as h,gt as i,ht as j,ft as k,F as l,wt as m,Nt as n,G as o,lt as p,f as q,nt as r,Tt as s,mt as t,St as u,Et as v,dt as w,At as x,it as y,Rt as z};
|
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.221",
|
|
4
4
|
"description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
54
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
55
|
-
"@lunora/wire": "1.0.0-alpha.
|
|
54
|
+
"@lunora/shard-engine": "1.0.0-alpha.172",
|
|
55
|
+
"@lunora/wire": "1.0.0-alpha.4",
|
|
56
56
|
"drizzle-orm": "1.0.0-rc.5"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./ctx-db-search-state-CaX6vwUz.mjs";import{b as S,c as s,a as i,r as l}from"./ctx-db-search-DhPvgSgA.mjs";import"./sql-exec-snQLgtvn.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{B as l,O as o,e as n,c as r,d as t,l as d,m as i,j as u,o as f,z as R,i as q,n as c,u as C,h as m,k as p,p as x,w as I,f as S,q as h,g as w,b as E,r as O,a as y,x as z,s as B,v as L,t as N}from"./sql-exec-snQLgtvn.mjs";import"./value-codec-C52YW-Do.mjs";export{l as BACKFILL_BATCH_SIZE,o as OCC_VERSION_COLUMN,n as columnRefSql,r as createIndexIfNotExists,t as decodeGlobalRow,d as decodeRow,i as decodeRows,u as dropIndexIfExists,f as fieldRefSql,R as forEachRowPaged,q as indexState,c as nextRowVersion,C as nullSafeEqualsSql,m as pathContainsNeedle,p as pathInList,x as pathTextReference,I as pathTypeGuardSql,S as qualifiedColumnRefSql,h as queryAll,w as queryBatch,E as queryRun,O as readRowsPage,y as runInOrder,z as serializeColumnValue,B as serializeDocumentColumn,L as serializeFieldValue,N as tableColumns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as y}from"@lunora/errors";import{needsWireEncoding as g,encodeWire as O,decodeWire as R}from"@lunora/wire";import{sql as p}from"drizzle-orm";import{runSqlGlobalTableMigrations as E}from"./runSqlGlobalTableMigrations-CIbF4adm.mjs";import{r as v,d as _,q as h}from"./sql-exec-snQLgtvn.mjs";const A=200,I=(t,e)=>{const o=r=>t.tables[r]?.shardMode?.kind==="global";return e&&e.length>0?e.filter(r=>o(r)):Object.keys(t.tables).filter(r=>o(r))},S=t=>g(t)?O(t):t,z=async function*(t,e,o,r){const c=I(e,r.tables),n=r.batchSize??A;await E(t,e,o);for(const a of c){const i=e.tables[a];let s,d=!0;for(;d;){const f=await v(t,o,a,s,n);for(const u of f)yield{doc:S(_(i,u)),table:a};const l=f.at(-1);l!==void 0&&(s=String(l.id)),d=f.length===n}}},w=t=>t?._meta?.column?.notNull===!1,L=(t,e)=>{const o=new Set;for(const[r,c]of Object.entries(t.shape)){if(e[r]!==null||c.kind!=="optional"||w(c))continue;const n=c._meta?.inner;w(n)||o.add(r)}return o.size===0?e:Object.fromEntries(Object.entries(e).filter(([r])=>!o.has(r)))},T=new Set(["_creationTime","_id"]),D=(t,e)=>Object.keys(e).find(o=>!T.has(o)&&!Object.hasOwn(t.shape,o)),$=t=>{const e=t._id,o=t._creationTime;if(e!==void 0&&(typeof e!="string"||e===""))return'field "_id": must be a non-empty string';if(o!==void 0&&(typeof o!="number"||!Number.isFinite(o)))return'field "_creationTime": must be a finite number'},F=(t,e,o)=>{const r=t.tables[e];if(!r)return`unknown table: ${e}`;const c=D(r,o);if(c!==void 0)return`unexpected field "${c}": not declared in table "${e}"`;const n=$(o);if(n!==void 0)return n;for(const[a,i]of Object.entries(r.shape)){const s=o[a],d=i.kind==="optional";if(s===void 0&&d)continue;const f=i.parse;if(typeof f=="function")try{f(s)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${a}": ${u}`}}},m=50,j=async(t,e,o,r,c,n)=>{const a=Object.keys(e.tables).filter(s=>s!==c&&e.tables[s]?.shardMode?.kind==="global"),i=[c,...a];for(let s=0;s<i.length;s+=m){const d=i.slice(s,s+m);if(!r){for(const b of d)if(await t.get(b,n)!==null)return b;continue}const f=d.map((b,k)=>p`SELECT ${p.raw(String(k))} AS slot FROM ${p.identifier(b)} WHERE ${p.identifier("id")} = ${n}`),u=(await h(r,o,p`${p.join(f,p` UNION ALL `)} ORDER BY slot LIMIT 1`))[0]?.slot;if(u!==void 0)return d[Number(u)]}},N=async(t,e,o,r,c,n,a)=>{let i;try{i=await j(t,e,o,r,c,n)}catch(s){const{body:d}=y(s,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:a,message:d.message,table:c}}}return i!==void 0&&i!==c?{error:{code:"ID_COLLISION",line:a,message:`_id "${n}" already belongs to table "${i}"`,table:c}}:{existingId:i===c?n:void 0}},B=async(t,e,o,r,c)=>{try{if(r!==void 0){const n={...o};return delete n._id,await t.replace(e,r,n,{allowExplicitId:!0}),{kind:"replaced"}}return await t.insert(e,o,{allowExplicitId:!0}),{inserted:e,kind:"inserted"}}catch(n){const{body:a}=y(n,{fallbackCode:r===void 0?"INSERT_FAILED":"REPLACE_FAILED"});return{error:{code:a.code,line:c,message:a.message,table:e},kind:"error"}}},W=async(t,e,o,r,c,n)=>{const{doc:a,table:i}=c;if(typeof i!="string"||i.length===0)return{error:{code:"BAD_ROW",line:n,message:"row is missing `table`",table:i},kind:"error"};if(e.tables[i]?.shardMode?.kind!=="global")return{kind:"skip"};if(!a||typeof a!="object"||Array.isArray(a))return{error:{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:i},kind:"error"};let s;try{s=R(a)}catch(b){return{error:{code:"BAD_ROW",line:n,message:b instanceof Error?b.message:String(b),table:i},kind:"error"}}s=L(e.tables[i],s);const d=F(e,i,s);if(d!==void 0)return{error:{code:"VALIDATION_ERROR",line:n,message:d,table:i},kind:"error"};if(r.dryRun===!0)return{kind:"checked"};const f=typeof s._id=="string"?s._id:void 0,l=f===void 0?{existingId:void 0}:await N(t,e,o,r.exec,i,f,n);if("error"in l)return{error:l.error,kind:"error"};const{existingId:u}=l;return u!==void 0&&r.onConflict!=="replace"?{kind:"conflict"}:B(t,i,s,u,n)},P=async(t,e,o,r)=>{const c=[],n={};let a=0,i=0,s=(r.startLine??1)-1;r.exec&&r.dryRun!==!0&&await E(r.exec,e,o);for(const d of r.rows){s+=1;const f=d.line??s,l=await W(t,e,o,r,d,f);switch(l.kind){case"conflict":{a+=1;break}case"error":{c.push(l.error);break}case"inserted":{n[l.inserted]=(n[l.inserted]??0)+1;break}case"replaced":{i+=1;break}}}return{conflicts:a,errors:c,inserted:n,replaced:i}};export{z as exportSqlGlobalRows,P as importSqlGlobalRows,I as selectGlobalTables};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as U}from"@lunora/shard-engine";import{needsWireEncoding as D,encodeWire as v}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as M}from"./runSqlGlobalTableMigrations-CIbF4adm.mjs";import{q as _,d as G}from"./sql-exec-snQLgtvn.mjs";import{s as K,e as W,a as T}from"./value-codec-C52YW-Do.mjs";const P=50,Y=500,H=30,j=200,X=(t,n,e)=>Math.min(Math.max(t,n),e),h=(t,n,e,a)=>X(Math.trunc(t!==void 0&&Number.isFinite(t)?t:n),e,a),J=(t,n)=>U(t)||n.name==="sqlite"&&t.startsWith("d1_"),g=t=>t.name==="postgres"?o`current_schema()`:o`DATABASE()`,p={columns:async(t,n,e)=>(n.name==="sqlite"?await _(t,n,o`PRAGMA table_info(${o.identifier(e)})`):await _(t,n,o`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${g(n)} AND table_name = ${e} ORDER BY ordinal_position`)).map(r=>String(r.name)),foreignKeys:async(t,n,e)=>{let a;return n.name==="sqlite"?a=o`PRAGMA foreign_key_list(${o.identifier(e)})`:n.name==="mysql"?a=o`SELECT column_name AS ${o.identifier("from")}, referenced_table_name AS ${o.identifier("table")} FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = ${e} AND referenced_table_name IS NOT NULL AND referenced_table_schema = DATABASE()`:a=o`SELECT kcu.column_name AS ${o.identifier("from")}, ccu.table_name AS ${o.identifier("table")} FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ${e} AND ccu.table_schema = current_schema()`,(await _(t,n,a)).map(s=>({from:String(s.from),target:String(s.table)}))},primaryKey:async(t,n,e)=>n.name==="sqlite"?(await _(t,n,o`PRAGMA table_info(${o.identifier(e)})`)).filter(s=>Number(s.pk??0)>0).map(s=>String(s.name)):(await _(t,n,o`SELECT kcu.column_name AS name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${g(n)} AND tc.table_name = ${e} ORDER BY kcu.ordinal_position`)).map(r=>String(r.name)),tables:async(t,n)=>(n.name==="sqlite"?await _(t,n,o`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`):await _(t,n,o`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ${g(n)} AND table_type = 'BASE TABLE' ORDER BY table_name`)).map(a=>String(a.name))},Q=/password|secret|token|hash|salt|credential/iu,V=new Map([["apikey",new Set(["key"])],["jwks",new Set(["privatekey"])],["twofactor",new Set(["backupcodes"])],["verification",new Set(["value"])]]),$=t=>t.toLowerCase().replaceAll("_",""),y=(t,n)=>Q.test(n)||V.get($(t))?.has($(n))===!0,E=(t,n)=>{const e=t.tables[n];return e?.shardMode?.kind==="global"?e:void 0},k=async(t,n)=>(await p.tables(t,n)).filter(a=>!J(a,n)),C=async(t,n,e,a)=>{if(await M(t,e,n),!(await k(t,n)).includes(a))throw new w("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},R=async(t,n,e,a=o``)=>{const r=await _(t,n,o`SELECT COUNT(*) AS c FROM ${o.identifier(e)}${a}`);return Number(r[0]?.c??0)},L=(t,n,e)=>E(t,n)!==void 0&&e==="_id"?"id":e,I=(t,n,e)=>{const a=E(t,n)?.shape[e];return a===void 0?void 0:W(a)},z=/^-?\d+$/u,O=100,B=(t,n)=>{if(n>O)throw new w("BAD_REQUEST",`the query over ${t} binds ${String(n)} parameters, and a statement takes at most ${String(O)} — remove some filters`)},Z=(t,n,e)=>{if(e)return t instanceof ArrayBuffer?new Uint8Array(t):t;if(n!=="bigint")return T(t);const a=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return T(a!==void 0&&z.test(a)?BigInt(a):t,n)},x=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new w("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new w("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},q=(t,n,e,a,r)=>{const s=[],i=E(t,e)===void 0&&n.name!=="sqlite";let m=0;for(const c of r??[]){if(x(c),!a.includes(c.column))throw new w("UNKNOWN_COLUMN",`unknown column: ${c.column}`,{status:404});if(E(t,e)===void 0&&y(e,c.column))throw new w("FORBIDDEN",`cannot filter on a redacted column: ${c.column}`,{status:403});const u=o.identifier(L(t,e,c.column));if(c.value===null||c.value===void 0)s.push(o`${u} IS NULL`);else{const l=Z(c.value,I(t,e,c.column),i);s.push(i&&n.name==="postgres"&&l instanceof Date?o`${u}::timestamptz = ${l}::timestamptz`:o`${u} = ${l}`),m+=1}}return{bound:m,where:s.length>0?o` WHERE ${o.join(s,o` AND `)}`:o``}},tt=(t,n,e)=>{const a=E(t,n);if(a)return G(a,e);const r={};for(const[s,i]of Object.entries(e))r[s]=i!=null&&y(n,s)?"•••":i;return r},F=async(t,n,e,a)=>{const r=E(e,a);return r?["_id","_creationTime",...Object.keys(r.shape)]:p.columns(t,n,a)},nt=async(t,n,e,a)=>{if(E(e,a))return;const r=await p.foreignKeys(t,n,a);if(r.length===0)return;const s={};for(const i of r){const{from:m,target:c}=i;s[m]??=c}return s},ut=async(t,n,e)=>{await M(t,n,e);const a=await k(t,e);return Promise.all(a.map(async r=>({name:r,rowCount:await R(t,e,r)})))},et=async(t,n,e,a,r)=>{if(E(e,a)!==void 0)return o`${o.identifier("id")}`;const s=await p.primaryKey(t,n,a);return s.length>0?o.join(s.map(i=>o.identifier(i)),o`, `):r.includes("id")?o`${o.identifier("id")}`:n.name==="sqlite"?o.raw("rowid"):o.join(r.map(i=>n.name==="postgres"?o`${o.identifier(i)}::text`:o.identifier(i)),o`, `)},lt=async(t,n,e,a)=>{const{table:r}=a;await C(t,e,n,r);const s=h(a.limit,P,1,Y),i=h(a.offset,0,0,Number.MAX_SAFE_INTEGER),m=await F(t,e,n,r),{bound:c,where:u}=q(n,e,r,m,a.filters);B(r,c);const l=await R(t,e,r,u),A=await et(t,e,n,r,m),b=(await _(t,e,o`SELECT * FROM ${o.identifier(r)}${u} ORDER BY ${A} LIMIT ${o.raw(String(s))} OFFSET ${o.raw(String(i))}`)).map(d=>{const f=tt(n,r,d);return D(f)?v(f):f}),S=await nt(t,e,n,r);return S===void 0?{columns:m,rows:b,total:l}:{columns:m,refs:S,rows:b,total:l}},ft=async(t,n,e,a)=>{const{column:r,table:s}=a;await C(t,e,n,s);const i=await F(t,e,n,s);if(!i.includes(r))throw new w("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const{bound:m,where:c}=q(n,e,s,i,a.filters);if(B(s,m),E(n,s)===void 0&&y(s,r)){const f=await R(t,e,s,c);return{truncated:!1,values:f===0?[]:[{count:f,value:"•••"}]}}const u=h(a.limit,H,1,j),l=o.identifier(L(n,s,r)),A=await _(t,e,o`SELECT ${l} AS value, COUNT(*) AS count FROM ${o.identifier(s)}${c} GROUP BY ${l} ORDER BY count DESC, ${l} ASC LIMIT ${o.raw(String(u+1))}`),N=A.length>u,b=N?A.slice(0,u):A,S=I(n,s,r)==="bigint",d=b.map(f=>({count:Number(f.count),value:S?K(f.value,"bigint"):f.value}));return{truncated:N,values:D(d)?v(d):d}};export{ft as facetSqlGlobalColumn,ut as listSqlGlobalTables,lt as readSqlGlobalTablePage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{needsWireEncoding as J}from"@lunora/wire";import{sql as e,SQL as v}from"drizzle-orm";import{a as T,s as x,e as U}from"./value-codec-C52YW-Do.mjs";const W=t=>{if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===null||n===Object.prototype},p=4;class A extends Error{}const S=t=>t.includes("."),w=t=>{const n=t.split(".");if(n.length>p||n.includes(""))throw new A(`field path "${t}" must have 1 to ${String(p)} non-empty segments`);return n},it=(t,n)=>{if(!S(n))return t[n];let s=t;for(const r of w(n)){if(!W(s)||!Object.hasOwn(s,r))return;s=s[r]}return s},B={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"},k=/^[A-Za-z_$][\w$]*$/u,I=t=>k.test(t)?t:`"${t.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,at="_version",R=t=>t==="_id"||t==="id"?"id":t,$=t=>e`${e.identifier(R(t))}`,C=t=>{try{return w(t)}catch(n){throw n instanceof A?new g("VALIDATION_ERROR",n.message):n}},q=new WeakMap,ct=t=>q.get(t),b=(t,n)=>{let s=e`${t}::jsonb`;for(const r of n)s=e`${s} -> ${r}::text`;return e`NULLIF(${s}, 'null'::jsonb)`},X=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} END`,K=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} #>> '{}' END`,L=(t,n)=>{const s=`$${n.map(r=>`.${I(r)}`).join("")}`;return e`NULLIF(JSON_EXTRACT(${t}, ${s}), CAST('null' AS JSON))`},V=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN ${L(t,n)} END`,z=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN JSON_UNQUOTE(${L(t,n)}) END`,lt=(t,n)=>t==="postgres"?e`(${n})::jsonb #>> '{}'`:e`JSON_UNQUOTE(${n})`,y=(t,n)=>{const[s="",...r]=C(n),o=$(s);return e`CASE WHEN json_valid(${o}) THEN ${e.raw(t)}(${o}, ${`$.${r.map(i=>I(i)).join(".")}`}) END`},G=(t,n)=>{if(!S(n))return $(n);if(t.name==="sqlite")return y("json_extract",n);const[s="",...r]=C(n),o=$(s),i=t.name==="postgres",a=i?X(o,r):V(o,r);return q.set(a,i?K(o,r):z(o,r)),a},D=new WeakMap,M=t=>e`CAST(CAST(${t} AS text) AS jsonb)`,ut=(t,n,s)=>{if(t.name==="sqlite")return e`NULLIF(${y("json_type",n)}, 'null') IN (${e.raw(B[s])})`;const r=G(t,n);if(t.name==="postgres")return e`jsonb_typeof(${r}) = ${e.raw(`'${s}'`)}`;const o={boolean:"'BOOLEAN'",number:"'INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL'",string:"'STRING'"}[s];return e`JSON_TYPE(${r}) IN (${e.raw(o)})`},Q=(t,n)=>{if(n===void 0)return n;if(typeof n=="bigint"||J(n))return t==="postgres"?e`CAST(NULL AS jsonb)`:e`CAST(NULL AS JSON)`;const s=JSON.stringify(n),r=t==="postgres"?e`${M(s)}`:e`CAST(${s} AS JSON)`;return D.set(r,s),r},dt=(t,n,s,r)=>{const o=[];let i=!1;for(const u of s){if(u===void 0)throw new g("BAD_REQUEST","an `in` list holds an undefined value");const d=u instanceof v?D.get(u):void 0;d===void 0?i=!0:o.push(d)}if(o.length===0||r&&i)return e`1 = 0`;const a=`[${o.join(",")}]`,c=t==="postgres"?e`SELECT e.v FROM jsonb_array_elements(${M(a)}) AS e(v)`:e`SELECT jt.v FROM JSON_TABLE(${a}, '$[*]' COLUMNS (v JSON PATH '$')) AS jt`;return r?e`${n} NOT IN (${c})`:e`${n} IN (${c})`},ft=(t,n,s,r)=>t.name==="sqlite"||!S(n)||s===null?r(s):Q(t.name,s),Et=(t,n)=>e`${e.identifier(t)}.${e.identifier(R(n))}`,$t=t=>{const n=[];for(const[s,r]of Object.entries(t.shape)){const o=r._meta?.column;o&&n.push([s,o])}return n},f=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.all(o,r)},l=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.run(o,r)},mt=(t,n,s)=>t==="postgres"?e`${n} IS NOT DISTINCT FROM ${s}`:t==="mysql"?e`${n} <=> ${s}`:e`${n} IS ${s}`,St={sql:t=>e`COALESCE(${t}, 0) + 1`,value:t=>(t==null?0:Number(t))+1},Nt=async(t,n,s)=>{if(s.length!==0){if(!t.batch){for(const r of s)await l(t,n,r);return}await t.batch(s.map(r=>n.render(r)))}},pt=async(t,n,s)=>{if(t.batch&&n.name==="sqlite"){await t.batch(s.map(r=>n.render(r)));return}for(const r of s)await l(t,n,r)},Ot=async(t,n,s)=>{const r=s.unique?e`UNIQUE `:e``,o=s.concurrently===!0&&n.name==="postgres"?e`CONCURRENTLY `:e``;if(n.name==="mysql"){try{await l(t,n,e`CREATE ${r}INDEX ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)}catch(i){const a=i;if(a.errno!==1061&&a.code!=="ER_DUP_KEYNAME"&&a.code!==1061)throw i}return}await l(t,n,e`CREATE ${r}INDEX ${o}IF NOT EXISTS ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)},j=(t,n)=>e`(SELECT ${e.identifier("c")}.oid FROM pg_index ${e.identifier("i")} JOIN pg_class ${e.identifier("c")} ON ${e.identifier("c")}.oid = ${e.identifier("i")}.indexrelid WHERE ${e.identifier("i")}.indrelid = to_regclass(quote_ident(${t})) AND ${e.identifier("c")}.relname = ${n}::name)`,_t=async(t,n,s,r)=>{if(n.name==="postgres"){const[o]=await f(t,n,e`SELECT quote_ident(${e.identifier("n")}.nspname) || '.' || quote_ident(${e.identifier("c")}.relname) AS ${e.identifier("qualified")} FROM pg_class ${e.identifier("c")} JOIN pg_namespace ${e.identifier("n")} ON ${e.identifier("n")}.oid = ${e.identifier("c")}.relnamespace WHERE ${e.identifier("c")}.oid = ${j(s,r)}`),i=o?.qualified;typeof i=="string"&&await l(t,n,e`DROP INDEX IF EXISTS ${e.raw(i)}`);return}if(n.name!=="mysql"){await l(t,n,e`DROP INDEX IF EXISTS ${e.identifier(r)}`);return}try{await l(t,n,e`DROP INDEX ${e.identifier(r)} ON ${e.identifier(s)}`)}catch(o){const i=o;if(i.errno!==1091&&i.code!=="ER_CANT_DROP_FIELD_OR_KEY"&&i.code!==1091)throw o}},ht=async(t,n,s,r)=>{switch(n.name){case"mysql":return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s} AND index_name = ${r} LIMIT 1`)).length>0?"valid":"absent";case"postgres":{const o=await f(t,n,e`SELECT indisvalid FROM pg_index WHERE indexrelid = ${j(s,r)}`);return o.length===0?"absent":o[0]?.indisvalid===!0?"valid":"invalid"}default:return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM sqlite_master WHERE type = 'index' AND name = ${r}`)).length>0?"valid":"absent"}},gt=T,m=t=>{if(t===void 0)return!1;if(t._meta?.column?.notNull===!1)return!0;switch(t.kind){case"any":case"null":return!0;case"literal":return t._meta?.value===null;case"optional":return m(t._meta?.inner);case"union":return t._meta?.members?.some(n=>m(n))===!0;default:return!1}},Y=t=>t.kind==="optional"&&!m(t),O=new WeakMap,P=t=>{let n=O.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([s,r])=>[s,U(r),Y(r)]),O.set(t,n)),n},_=new WeakMap,Z=(t,n)=>{let s=_.get(t);return s===void 0&&(s=new Map(P(t).map(([r,o])=>[r,o])),_.set(t,s)),s.get(n)},Tt=(t,n,s)=>T(s,Z(t,n)),tt=(t,n)=>{const s={};for(const[r,o,i]of P(t)){const a=n[r];a===void 0||i&&a===null||(s[r]=x(a,o))}return s._id=n.id,s._creationTime=n._creationTime,s},F=(t,n)=>n?tt(t,n):null,At=(t,n)=>{const s=[];for(const r of n){const o=F(t,r);o&&s.push(o)}return s},h=500,nt=(t,n,s,r,o)=>{const i=e`${e.identifier(s)}.${e.identifier("id")}`,a=r===void 0?e``:e` WHERE ${i} > ${r}`;return f(t,n,e`SELECT * FROM ${e.identifier(s)}${a} ORDER BY ${i} ASC LIMIT ${e.raw(String(o))}`)},wt=async(t,n,s,r,o,i={})=>{let a=i.after,c=i.limit,u=!0;for(;u&&(c===void 0||c>0);){const d=c===void 0?h:Math.min(h,c),E=await nt(t,n,r,a,d);for(const H of E){const N=F(s,H);N&&await o(N)}a=E.at(-1)?.id,u=E.length===d,c=c===void 0?void 0:c-E.length}};export{h as B,at as O,pt as a,l as b,Ot as c,tt as d,$ as e,Et as f,Nt as g,lt as h,ht as i,_t as j,dt as k,F as l,At as m,St as n,G as o,ct as p,f as q,nt as r,Tt as s,$t as t,mt as u,ft as v,ut as w,gt as x,it as y,wt as z};
|