@lunora/d1 1.0.0-alpha.24 → 1.0.0-alpha.240
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +201 -104
- package/README.md +3 -3
- package/dist/dialect.d.mts +69 -30
- package/dist/dialect.d.ts +69 -30
- package/dist/dialect.mjs +1 -36
- package/dist/index.d.mts +402 -257
- package/dist/index.d.ts +402 -257
- package/dist/index.mjs +1 -7
- package/dist/packem_shared/ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs +1 -0
- package/dist/packem_shared/D1Client-CzS0Qfa6.mjs +1 -0
- package/dist/packem_shared/D1TimeoutError-D4YUqZPk.mjs +1 -0
- package/dist/packem_shared/GlobalImportStagingError-d4vGUGYx.mjs +1 -0
- package/dist/packem_shared/MigrationRunner-CD5zcqp6.mjs +8 -0
- package/dist/packem_shared/OCC_VERSION_COLUMN-ByC64Jgx.mjs +1 -0
- package/dist/packem_shared/applySqlMigrationFiles-CUiRKrxP.mjs +8 -0
- package/dist/packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs +1 -0
- package/dist/packem_shared/d1QueryTag-BcEGW4q1.mjs +1 -0
- package/dist/packem_shared/exportGlobalRows-IncHgv-p.mjs +1 -0
- package/dist/packem_shared/facetGlobalColumn-BqK1_P3S.mjs +1 -0
- package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
- package/dist/packem_shared/sqliteDialect-B_3JNtdq.mjs +1 -0
- package/package.json +8 -6
- package/dist/packem_shared/D1Client-DA3flo1o.mjs +0 -143
- package/dist/packem_shared/MigrationRunner-BQx8HAGh.mjs +0 -154
- package/dist/packem_shared/createD1CtxDb-BMR8J0dT.mjs +0 -14
- package/dist/packem_shared/exportGlobalRows-BgfNSwCG.mjs +0 -122
- package/dist/packem_shared/facetGlobalColumn-C6u_WMIY.mjs +0 -142
- package/dist/packem_shared/quoteIdentifier-B-ZeSe1V.mjs +0 -3
- package/dist/packem_shared/sqliteDialect-DqYnHPuu.mjs +0 -27
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { D1Client, D1Session } from './packem_shared/D1Client-DA3flo1o.mjs';
|
|
3
|
-
export { createD1CtxDb, readD1CdcChanges, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, trimD1CdcChanges } from './packem_shared/createD1CtxDb-BMR8J0dT.mjs';
|
|
4
|
-
export { facetGlobalColumn, listGlobalTables, readGlobalTablePage } from './packem_shared/facetGlobalColumn-C6u_WMIY.mjs';
|
|
5
|
-
export { MigrationRunner } from './packem_shared/MigrationRunner-BQx8HAGh.mjs';
|
|
6
|
-
export { default as sqliteDialect } from './packem_shared/sqliteDialect-DqYnHPuu.mjs';
|
|
7
|
-
export { createSqlCtxDb } from '@lunora/sql-store';
|
|
1
|
+
import{exportGlobalRows as e,importGlobalRows as t}from"./packem_shared/exportGlobalRows-IncHgv-p.mjs";import{D1Client as l,D1Session as i}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as s,createD1CtxDb as p,readD1CdcChanges as g,runD1AggregateMigrations as m,runD1CdcMigration as D,runD1GlobalTableMigrations as b,runD1RankMigrations as x,runD1SearchMigrations as f,sweepD1CdcRetention as c}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{GlobalImportStagingError as d,abortStagedGlobalRows as u,commitStagedGlobalRows as R,stageGlobalRows as G}from"./packem_shared/GlobalImportStagingError-d4vGUGYx.mjs";import{facetGlobalColumn as T,listGlobalTables as M,readGlobalTablePage as w}from"./packem_shared/facetGlobalColumn-BqK1_P3S.mjs";import{MigrationRunner as E}from"./packem_shared/MigrationRunner-CD5zcqp6.mjs";import{d1QueryTag as q,emitD1QueryCost as A,readD1QueryCost as I}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as k,isTransientD1Error as L,retryingExec as _,withD1Retry as F}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{applySqlMigrationFiles as O}from"./packem_shared/applySqlMigrationFiles-CUiRKrxP.mjs";import{default as U}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as W}from"@lunora/shard-engine";import{ALLOW_DESTRUCTIVE_MARKER as v}from"./packem_shared/ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{createSqlCtxDb as B,selectGlobalTables as H}from"@lunora/sql-store";export{v as ALLOW_DESTRUCTIVE_MARKER,l as D1Client,i as D1Session,k as D1TimeoutError,d as GlobalImportStagingError,E as MigrationRunner,u as abortStagedGlobalRows,W as applyCdcChanges,O as applySqlMigrationFiles,s as backfillD1SearchIndexes,R as commitStagedGlobalRows,p as createD1CtxDb,B as createSqlCtxDb,q as d1QueryTag,A as emitD1QueryCost,e as exportGlobalRows,T as facetGlobalColumn,t as importGlobalRows,L as isTransientD1Error,M as listGlobalTables,g as readD1CdcChanges,I as readD1QueryCost,w as readGlobalTablePage,_ as retryingExec,m as runD1AggregateMigrations,D as runD1CdcMigration,b as runD1GlobalTableMigrations,x as runD1RankMigrations,f as runD1SearchMigrations,H as selectGlobalTables,U as sqliteDialect,G as stageGlobalRows,c as sweepD1CdcRetention,F as withD1Retry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="-- lunora:allow-destructive";export{o as ALLOW_DESTRUCTIVE_MARKER};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{drizzle as i}from"drizzle-orm/d1";import{isReadOnlyD1Sql as o,withD1Retry as a}from"./D1TimeoutError-D4YUqZPk.mjs";const c=(s,e)=>{if(s.size<e)return;const t=s.keys().next().value;t!==void 0&&s.delete(t)},l=256,h=(s,e,t)=>{const r=s.get(t);if(r)return s.delete(t),s.set(t,r),r;const n=e(t);return c(s,l),s.set(t,n),n},d="first-unconstrained";class u{session;stmtCache=new Map;constructor(e){this.session=e}prepare(e){return h(this.stmtCache,t=>this.session.prepare(t),e)}async run(e,...t){return this.prepare(e).bind(...t).run()}async all(e,...t){const r=async()=>this.prepare(e).bind(...t).all();return o(e)?a(r):r()}async first(e,...t){const r=async()=>this.prepare(e).bind(...t).first();return o(e)?a(r):r()}getBookmark(){return this.session.getBookmark()??void 0}}class b{db;stmtCache=new Map;drizzleHandle;constructor(e){this.db=e}withSession(e){const t=this.db.withSession(e??d);return new u(t)}prepare(e){return h(this.stmtCache,t=>this.db.prepare(t),e)}get drizzle(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=i(this.db,{logger:!1}),this.drizzleHandle)}drizzleSession(e){const t=this.db.withSession(e??d);return i(t,{logger:!1})}async batch(e){return this.drizzle.batch(e)}get raw(){return this.db}}export{b as D1Client,u as D1Session};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h,unreachable as f}from"@lunora/errors";const y=["storage operation exceeded timeout","network connection lost","internal error while starting up d1 db storage","exceeded its memory limit","caused object to be reset"],M=3,S=50,b=1e3,D=2e3,p=/^[\s(]*(?:select|pragma|explain)\b/iu,_=t=>p.test(t),A=t=>t instanceof Error?`${t.name}: ${t.message}`.toLowerCase():typeof t=="string"?t.toLowerCase():"",I=t=>{const e=A(t);return e.length===0?!1:y.some(n=>e.includes(n))},N=t=>{const e=Math.min(b,S*2**(t-1));return Math.round(Math.random()*e)},L=async t=>new Promise(e=>{setTimeout(e,t)});class l extends Error{timeoutMs;constructor(e){super(`@lunora/d1: operation exceeded its ${String(e)}ms timeout and was abandoned (the underlying D1 call may still be running)`),this.name="D1TimeoutError",this.timeoutMs=e}}const R=async(t,e)=>{let n;try{return await Promise.race([t(),new Promise((o,r)=>{n=setTimeout(()=>{r(new l(e))},e)})])}finally{n!==void 0&&clearTimeout(n)}},x=async(t,e={})=>{const n=e.attempts??M;if(!Number.isInteger(n)||n<1)throw new h("BAD_REQUEST","@lunora/d1: `attempts` must be an integer >= 1");const o=e.sleep??L,{deadlineMs:r,timeoutMs:i}=e,d=Date.now(),w=r===void 0&&i===void 0,c=()=>r===void 0?Number.POSITIVE_INFINITY:r-(Date.now()-d);for(let s=1;s<=n;s+=1){const u=Math.min(i??Number.POSITIVE_INFINITY,Math.max(c(),0)),E=Date.now();try{return await(Number.isFinite(u)?R(t,u):t())}catch(a){const g=a instanceof l||I(a),T=w&&Date.now()-E>=D,m=c();if(s===n||!g||T||m<=0)throw a;await o(Math.min(N(s),m))}}return f("@lunora/d1: retry loop exited without returning or throwing")},P=(t,e)=>({...t,all:async(n,o)=>_(n)?x(async()=>t.all(n,o),e):t.all(n,o)});export{l as D1TimeoutError,_ as isReadOnlyD1Sql,I as isTransientD1Error,P as retryingExec,x as withD1Retry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as g}from"@lunora/errors";import{prepareGlobalImportRow as h}from"@lunora/sql-store";import{encodeWire as A,decodeWire as D}from"@lunora/wire";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";const E="__lunora_import_stage__",c="__lunora_import_session__",u=1440*60*1e3,p=200,M=(o,s,t)=>{const e=[],i=[];let l=(s.startLine??1)-1;for(const a of s.rows){l+=1;const r=a.line??l;if(!t.has(a.table)){e.push({code:"BAD_ROW",line:r,message:`table "${a.table}" is not in this replace import's tables`,table:a.table});continue}const n=h(o,a,r);n.kind==="settled"?n.outcome.kind==="error"&&e.push(n.outcome.error):n.kind==="delete"?e.push({code:"BAD_ROW",line:r,message:'a replace import does not take `op: "delete"` rows',table:a.table}):n.explicitId===void 0?e.push({code:"BAD_ROW",line:r,message:"a replace import row must carry its `_id`",table:n.table}):i.push({decoded:n.decoded,id:n.explicitId,line:r,table:n.table})}return{errors:e,ready:i}},$=async(o,s,t)=>(await o.all(`SELECT 1 FROM ${f(s)} WHERE id = ? LIMIT 1`,[t])).length>0,y=async(o,s,t)=>{try{if(await $(s,t.table,t.id)){const e={...t.decoded};delete e._id,await o.replace(t.table,t.id,e,{allowExplicitId:!0})}else await o.insert(t.table,t.decoded,{allowExplicitId:!0});return}catch(e){const{body:i}=g(e,{fallbackCode:"INSERT_FAILED"});return{code:i.code,line:t.line,message:i.message,table:t.table}}};class R extends Error{code;constructor(s,t){super(t),this.name="GlobalImportStagingError",this.code=s}}const L=async o=>{await o.run(`CREATE TABLE IF NOT EXISTS "${E}" (seq INTEGER PRIMARY KEY AUTOINCREMENT, session TEXT NOT NULL, tbl TEXT NOT NULL, id TEXT NOT NULL, line INTEGER NOT NULL, doc TEXT NOT NULL)`,[]),await o.run(`CREATE INDEX IF NOT EXISTS "${E}_by_session" ON "${E}" (session, tbl, id)`,[]),await o.run(`CREATE TABLE IF NOT EXISTS "${c}" (session TEXT PRIMARY KEY, state TEXT NOT NULL, generation TEXT NOT NULL, expires_at INTEGER NOT NULL, result TEXT)`,[])},N=async(o,s)=>{if(o.batch){await o.batch(s);return}for(const{params:t,sql:e}of s)await o.run(e,t)},w=async(o,s)=>{await L(o),await N(o,[{params:[s],sql:`DELETE FROM "${E}" WHERE session IN (SELECT session FROM "${c}" WHERE expires_at < ? AND state IN ('staging', 'committed'))`},{params:[s],sql:`DELETE FROM "${c}" WHERE expires_at < ? AND state IN ('staging', 'committed')`}])},b=`INSERT INTO "${c}" (session, state, generation, expires_at) VALUES (?, 'staging', ?, ?) ON CONFLICT (session) DO UPDATE SET expires_at = excluded.expires_at`,_=async(o,s,t)=>{const[e]=await o.all(`SELECT state, generation, result FROM "${c}" WHERE session = ?`,[s]);if(e===void 0)return;const i=String(e.state);if(i!=="staging"&&i!=="committed")throw new R("IMPORT_SESSION_CORRUPT",`import session "${s}" has an unreadable state in D1`);if(String(e.generation)!==t)throw new R("IMPORT_SESSION_STALE",`import session "${s}" in D1 belongs to an earlier session of the same id`);return typeof e.result=="string"?{generation:t,result:JSON.parse(e.result),state:i}:{generation:t,state:i}},U=async(o,s,t,e=Date.now())=>{if(await w(o,e),(await _(o,t.session,t.generation))?.state==="committed")throw new R("IMPORT_SESSION_COMMITTED",`import session "${t.session}" is already committed`);const l=new Set(t.tables.filter(d=>s.tables[d]?.shardMode?.kind==="global")),{errors:a,ready:r}=M(s,t,l);if(a.length>0)return{errors:a,staged:{}};const n={};return await N(o,[{params:[t.session,t.generation,e+u],sql:b},...r.map(({decoded:d,id:T,line:S,table:m})=>(n[m]=(n[m]??0)+1,{params:[t.session,m,T,S,JSON.stringify(A(d))],sql:`INSERT INTO "${E}" (session, tbl, id, line, doc) VALUES (?, ?, ?, ?, ?)`}))]),{errors:[],staged:n}},C=async(o,s,t)=>{const e={};let i=0;for(;;){const l=await s.all(`SELECT seq, tbl, id, line, doc FROM "${E}" WHERE session = ? AND seq > ? ORDER BY seq LIMIT ?`,[t,i,p]),a=[];for(const r of l){const n=String(r.tbl),d=String(r.id),T=D(JSON.parse(String(r.doc))),S=await y(o,s,{decoded:T,id:d,line:Number(r.line),table:n});S===void 0?e[n]=(e[n]??0)+1:a.push(S)}if(a.length>0||l.length<p)return{errors:a,inserted:e};i=Number(l.at(-1)?.seq)}},O=o=>new R("IMPORT_SESSION_EXPIRED",`import session "${o}" has no staged .global() rows (expired, or aborted)`),I=async(o,s)=>(await o.all(`SELECT 1 FROM "${E}" WHERE session = ? LIMIT 1`,[s])).length>0,F=async(o,s,t,e,i)=>{if((await s.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",[e])).length===0)return 0;let a=0;for(;;){const r=await s.all(`SELECT "id" FROM ${f(e)} WHERE "id" NOT IN (SELECT id FROM "${E}" WHERE session = ? AND tbl = ?)${i?` AND EXISTS (SELECT 1 FROM "${E}" WHERE session = ?)`:""} LIMIT ?`,i?[t,e,t,p]:[t,e,p]);for(const{id:n}of r)await o.delete(e,String(n),{hard:!0});if(a+=r.length,r.length<p){if(i&&!await I(s,t))throw O(t);return a}}},G=async(o,s,t,e,i=Date.now())=>{await w(s,i);const l=await _(s,e.session,e.generation);if(l?.state==="committed"&&l.result!==void 0)return l.result;if(e.staged&&(l===void 0||!await I(s,e.session)))throw O(e.session);await s.run(b,[e.session,e.generation,i+u]);const{errors:a,inserted:r}=await C(o,s,e.session);if(a.length>0)return{conflicts:0,deleted:{},errors:a,inserted:r};const n={};for(const T of e.tables.filter(S=>t.tables[S]?.shardMode?.kind==="global")){if(e.staged&&!await I(s,e.session))throw O(e.session);n[T]=await F(o,s,e.session,T,e.staged)}const d={conflicts:0,deleted:n,errors:[],inserted:r};return await N(s,[{params:[e.session,e.generation,i+u,JSON.stringify(d)],sql:`INSERT INTO "${c}" (session, state, generation, expires_at, result) VALUES (?, 'committed', ?, ?, ?) ON CONFLICT (session) DO UPDATE SET state = 'committed', expires_at = excluded.expires_at, result = excluded.result`},{params:[e.session],sql:`DELETE FROM "${E}" WHERE session = ?`}]),d},P=async(o,s,t)=>{await L(o),await N(o,[{params:[s,s,t],sql:`DELETE FROM "${E}" WHERE session = ? AND EXISTS (SELECT 1 FROM "${c}" WHERE session = ? AND generation = ?)`},{params:[s,t],sql:`DELETE FROM "${c}" WHERE session = ? AND generation = ?`}])};export{R as GlobalImportStagingError,P as abortStagedGlobalRows,G as commitStagedGlobalRows,U as stageGlobalRows};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{sql as u}from"drizzle-orm";import{ALLOW_DESTRUCTIVE_MARKER as $}from"./ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{D1Client as C}from"./D1Client-CzS0Qfa6.mjs";const R="__drizzle_migrations",P=`CREATE TABLE IF NOT EXISTS ${R} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC, version INTEGER)`,b=`CREATE UNIQUE INDEX IF NOT EXISTS ${R}_version ON ${R} (version)`,L=/\s/u,G=/[$\w]/u,S=String.raw`(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)`,v=/(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/uy,O=new RegExp(String.raw`CREATE${S}+(?:TEMP${S}+|TEMPORARY${S}+)?TRIGGER\b`,"iuy"),x=/^[0-9a-f]{64}$/u,N=String.raw`[$\w\u{80}-\u{10FFFF}]`,_=`${N}+`,A=n=>new RegExp(String.raw`(?<!${N})${n.replaceAll(" ",String.raw`\s+`)}(?!${N})`,"iu"),M=n=>new RegExp(String.raw`^\s*ALTER\s+TABLE\s+${_}(?:\s*\.\s*${_})?\s+${n}\b`,"iu"),B=[["DROP",/^\s*DROP\s+(?:TABLE|INDEX|VIEW|TRIGGER)\b/iu],["DROP",M("DROP")],["RENAME",M("RENAME")],["TRUNCATE",/^\s*TRUNCATE\b/iu],["INSERT OR REPLACE",A("INSERT OR REPLACE")],["REPLACE INTO",A("REPLACE INTO")],["UPDATE OR REPLACE",A("UPDATE OR REPLACE")],["ON CONFLICT REPLACE",A("ON CONFLICT REPLACE")]],V=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/iu,F={'"':'"',"'":"'","[":"]","`":"`"},H=new RegExp(String.raw`UNIQUE constraint failed:\s*${R}\.(?:hash|version)`,"iu"),y=n=>`Migration "${n.name}" (v${String(n.version)})`,D=(n,e,t)=>({codeIndex:e,ownLine:n.slice(n.lastIndexOf(`
|
|
2
|
+
`,e-1)+1,e).trim()==="",text:t}),k=(n,e,t=0,c=!1)=>{v.lastIndex=t,v.exec(n),O.lastIndex=v.lastIndex;const i=O.test(n),d=[];let s="",o,l,r=0,a=0,h,T="",I=!1,f=!1;for(let m=t;m<n.length;m+=1){const E=n.charAt(m),g=n.charAt(m+1);if(l==="line"){E===`
|
|
3
|
+
`&&(d.push(D(s,a,n.slice(r,m))),l=void 0),s+=E===`
|
|
4
|
+
`?`
|
|
5
|
+
`:" ";continue}if(l==="block"){s+=" ",E==="*"&&g==="/"&&(s+=" ",l=void 0,m+=1);continue}if(o!==void 0){s+=" ",E===o&&o!=="]"&&g===o?(s+=" ",m+=1):E===o&&(o=void 0);continue}if(E==="-"&&g==="-"||E==="/"&&g==="*"){l=E==="-"?"line":"block",r=m,a=s.length,s+=" ",m+=1;continue}if(h!==void 0){if(!L.test(E))throw new w("INTERNAL",`${e} contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);s+=E;continue}if(i){if(G.test(E)){T+=E,s+=E;continue}const p=T.toUpperCase();T="",p!==""?(I=f&&p==="END",f=!1):E!==";"&&!L.test(E)&&(I=!1,f=!1)}if(o=F[E],o!==void 0){s+=" _ ";continue}if(s+=E,E===";"){if(i&&!I)f=!0;else if(h=m,c)break}}return l==="line"&&d.push(D(s,a,n.slice(r))),{code:s,end:h===void 0?n.length:h+1,lineComments:d,statementText:n.slice(t,h??n.length).trim()}},q=n=>V.test(n.code),Q=n=>{let e;for(const[t,c]of B){const i=c.exec(n.code),d=i===null?void 0:i.index+i[0].length-i[0].trimStart().length;d!==void 0&&(e===void 0||d<e.index)&&(e={index:d,statement:t})}return e},K=(n,e)=>{if(q(e))throw new w("INTERNAL",`${n} is transaction control (BEGIN/COMMIT/END/ROLLBACK/SAVEPOINT/RELEASE). Each migration already runs atomically with its tracking row in one batch(); remove it.`);const t=Q(e);if(t===void 0)return;if(!e.lineComments.some(i=>i.ownLine&&i.codeIndex<t.index&&i.text.trimEnd()===$))throw new w("MIGRATION_DESTRUCTIVE",`${n} has not run yet and contains a destructive statement (${t.statement}). If it is meant to discard data or rename what readers depend on, add a \`${$}\` line comment on its own line before the statement. Only pending migrations are checked, so never add it to one that already ran: that changes its hash and is refused as drift.`)},U=async n=>{const e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(c=>c.toString(16).padStart(2,"0")).join("")},W=/^\uFEFF/u,X=n=>{let e=n.length;for(;e>0&&n[e-1]===`
|
|
6
|
+
`;)e-=1;return n.slice(0,e)},z=n=>X(n.replace(W,"").replaceAll(`\r
|
|
7
|
+
`,`
|
|
8
|
+
`)),j=async n=>({normalized:await U(z(n)),raw:await U(n)}),Y=(n,e)=>n===e?.normalized||n===e?.raw;class te{client;migrations;constructor(e,t){this.client=e instanceof C?e:new C(e),this.migrations=[...t].toSorted((c,i)=>c.version-i.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.ensureTrackingTable();const e=await Promise.all(this.migrations.map(async r=>j(r.sql))),t=await this.readTrackingRows(e),c=new Map(t.filter(r=>r.version!==null).map(r=>[r.version,r.hash])),i=[];for(const[r,a]of this.migrations.entries()){const h=c.get(a.version),T=String(e[r]?.normalized);if(h===void 0)i.push({hash:T,migration:a});else if(!Y(h,e[r]))throw new w("MIGRATION_DRIFT",`${y(a)} was already applied from different SQL (recorded sha256 ${h}, now ${T}). An applied migration is never re-run: revert the edit and put the change in a new migration. If the edit is inert (a comment, whitespace, line endings), record the new text as applied: UPDATE ${R} SET hash = '${T}' WHERE version = ${String(a.version)};`)}const d=t.filter(r=>r.version===null);if(i.length>0&&d.length>0){const r=i.map(({migration:a})=>a.version);throw new w("MIGRATION_DRIFT",`${R} holds ${String(d.length)} row(s) recorded before versions were tracked whose SQL matches no current migration (id ${d.map(a=>String(a.id)).join(", ")}), and ${r.map(a=>`v${String(a)}`).join(", ")} ${r.length===1?"is":"are"} not recorded as applied — one of them may be an edited copy of what already ran. Refusing to guess: give each row the version it recorded (UPDATE ${R} SET version = <n> WHERE id = <id>; for a migration that no longer exists, any version no current migration uses), then run again.`)}const s=new Map(i.map(({hash:r,migration:a})=>{const h=y(a),T=k(a.sql,h);return K(h,T),[a.version,{hash:r,migration:a,statementText:T.statementText}]})),o=[],l=[];for(const r of this.migrations){const a=s.get(r.version),h={name:r.name,version:r.version};if(a===void 0){l.push(h);continue}await this.applyOne(a)?o.push(h):l.push(h)}return{applied:o,skipped:l}}async hasVersionColumn(){return(await this.client.drizzle.all(u.raw(`SELECT name FROM pragma_table_info('${R}') WHERE name = 'version'`))).length>0}async ensureTrackingTable(){if(await this.client.drizzle.run(u.raw(P)),!await this.hasVersionColumn())try{await this.client.drizzle.run(u.raw(`ALTER TABLE ${R} ADD COLUMN version INTEGER`))}catch(e){if(!await this.hasVersionColumn())throw e}await this.client.drizzle.run(u.raw(b))}async readTrackingRows(e){const t=u.raw(`SELECT id, hash, version FROM ${R} ORDER BY id`),c=await this.client.drizzle.all(t),i=new Map(this.migrations.flatMap((o,l)=>[[String(e[l]?.raw),o.version],[String(e[l]?.normalized),o.version]])),d=new Set(c.map(o=>o.version).filter(o=>o!==null));let s=!1;for(const o of c){const l=o.version===null?i.get(o.hash):void 0;l===void 0||d.has(l)||(await this.client.drizzle.run(u`UPDATE ${u.raw(R)} SET version = ${l} WHERE id = ${o.id} AND version IS NULL`),d.add(l),s=!0)}return s?await this.client.drizzle.all(t):c}async applyOne({hash:e,migration:t,statementText:c}){if(!x.test(e))throw new w("INTERNAL",`migration "${t.name}" produced a non-hex hash; refusing to inline into SQL`);const i=`INSERT INTO ${R} (hash, created_at, version) VALUES ('${e}', ${String(Date.now())}, ${String(t.version)})`,d=[this.client.drizzle.run(u.raw(c)),this.client.drizzle.run(u.raw(i))];try{await this.client.batch(d)}catch(s){if(H.test(s instanceof Error?s.message:String(s)))return!1;throw s}return!0}assertUniqueVersions(){const e=new Set;for(const t of this.migrations){if(!Number.isSafeInteger(t.version))throw new w("INTERNAL",`Migration "${t.name}" has version ${String(t.version)}; a version must be an integer`);if(e.has(t.version))throw new w("INTERNAL",`Duplicate migration version ${String(t.version)}`);e.add(t.version)}}assertUniqueSql(){const e=new Map;for(const t of this.migrations){const c=z(t.sql),i=e.get(c);if(i!==void 0)throw new w("INTERNAL",`Migrations ${String(i)} and ${String(t.version)} have identical SQL — bump the content, not just the version.`);e.set(c,t.version)}}}export{$ as ALLOW_DESTRUCTIVE_MARKER,te as MigrationRunner,R as TRACKING_TABLE_NAME,Q as firstDestructive,q as isTransactionControl,z as normalizeMigrationText,k as scanStatement,U as sha256Hex};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="_version";export{o as OCC_VERSION_COLUMN};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{globalColumnBackfill as z}from"@lunora/sql-store";import{sql as A}from"drizzle-orm";import{D1Client as Q}from"./D1Client-CzS0Qfa6.mjs";import{sha256Hex as V,normalizeMigrationText as X,scanStatement as q,firstDestructive as H,isTransactionControl as K}from"./MigrationRunner-CD5zcqp6.mjs";const _="__lunora_sql_migrations",W=`CREATE TABLE IF NOT EXISTS ${_} (name TEXT PRIMARY KEY, sha256 TEXT NOT NULL, applied_at INTEGER NOT NULL, baselined INTEGER NOT NULL DEFAULT 0, written_by TEXT NOT NULL DEFAULT 'root')`,j=/^\w[\w.-]*\.sql$/u,Y=new RegExp(String.raw`UNIQUE constraint failed:\s*${_}\.name`,"iu"),Z=/duplicate column name/iu,$="`",p=String.raw`"(?:[^"]|"")+"|\[[^\]]+\]|${$}(?:[^${$}]|${$}${$})+${$}|[_a-z]\w*`,c=String.raw`(?:\s|--[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)+`,I=String.raw`(?:\s|--[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*`,J=new RegExp(String.raw`^${I}`,"u"),T=String.raw`(?:(?:${p})${I}\.${I})?`,ee=new RegExp(String.raw`^ALTER${c}TABLE${c}${T}(${p})${c}ADD${c}(?:COLUMN${c})?(${p})`,"iu"),te=new RegExp(String.raw`^(?:DROP${c}TABLE(?:${c}IF${c}EXISTS)?${c}${T}(${p})|CREATE${c}TABLE(?!${c}IF${c}NOT${c}EXISTS\b)${c}${T}(${p})|ALTER${c}TABLE${c}${T}(${p})${c}(?:RENAME|DROP)\b)`,"iu"),ne=/^(?:WITH|INSERT|UPDATE|DELETE|REPLACE)\b/iu,re=new RegExp(String.raw`^CREATE${c}TABLE(?:${c}IF${c}NOT${c}EXISTS)?${c}${T}(?:${p})${c}AS\b`,"iu"),g=String.raw`[_a-z][\w$]*`,L=String.raw`(?:${g}\s*\.\s*)?`,se=new RegExp(String.raw`^\s*CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+${L}${g}\s*\(`,"iu"),ae=new RegExp(String.raw`^\s*CREATE\s+INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+${L}${g}\s+ON\s+${L}${g}\s*\(([^()]*)\)[\s;]*$`,"iu"),oe=new RegExp(String.raw`^\s*${g}(?:\s+COLLATE\s+${g})?(?:\s+(?:ASC|DESC))?\s*$`,"iu"),ie=new RegExp(String.raw`^\s*ALTER\s+TABLE\s+${L}${g}\s+ADD\s+(?:COLUMN\s+)?${g}`,"iu"),ce=/\b(?:DEFAULT|GENERATED|AS|CHECK|REFERENCES|UNIQUE|NOT\s+NULL|NOTNULL)\b/iu,le=/\bREFERENCES\b/iu,de=/__lunora_|__drizzle_|__cdc_|__agg_|__rank_|__fts_|sqlite_|_cf_/iu,ue=new RegExp(String.raw`\btemp["\]${$}]?${I}\.`,"iu"),Ee=new RegExp(String.raw`^PRAGMA${c}${T}(?:foreign_keys|"foreign_keys")${I}(?:=|\()`,"iu"),N=t=>{if(t.startsWith("["))return t.slice(1,-1);if(t.startsWith('"')||t.startsWith("`")){const e=t.charAt(0);return t.slice(1,-1).replaceAll(e+e,e)}return t},f=t=>t.replaceAll(/[A-Z]+/gu,e=>e.toLowerCase()),O=t=>t.slice(J.exec(t)?.[0].length??0),S=t=>t.replaceAll(/--[^\n]*/gu," ").replaceAll(/\s+/gu," ").trim(),M=t=>Ee.test(O(t)),b=t=>{const e=ee.exec(O(t));if(e!==null)return{column:N(e[2]??""),table:N(e[1]??"")}},he=t=>{const e=te.exec(O(t)),n=e?.[1]??e?.[2]??e?.[3];return n===void 0?void 0:N(n)},me=async(t,e,n)=>{const r=`"${e.replaceAll('"','""')}"`,s=await t.drizzle.all(A.raw(`PRAGMA table_info(${r})`)),o=f(n);return s.some(i=>f(i.name)===o)},fe=t=>{if(de.test(t.statementText)||ue.test(t.statementText))return!1;const e=ie.exec(t.code);if(e!==null)return!ce.test(t.code.slice(e[0].length));if(le.test(t.code))return!1;const n=ae.exec(t.code);return n!==null?(n[1]??"").split(",").every(r=>oe.test(r)):se.test(t.code)},U=(t,e)=>{const n=he(t);n!==void 0&&e.add(f(n))},F=t=>{const e=O(t);return ne.test(e)||re.test(e)},pe=(t,e)=>e||F(t),B=()=>({present:new Map,stale:new Set}),we=new RegExp(String.raw`^ALTER${c}TABLE${c}${T}(${p})${c}DROP${c}(?:COLUMN${c})?(${p})`,"iu"),P=t=>{const e=we.exec(O(t));if(e!==null)return{column:N(e[2]??""),table:N(e[1]??"")}},Re=t=>{const e=b(t);if(e!==void 0)return{column:f(e.column),present:!0,table:f(e.table)};const n=P(t);return n===void 0?void 0:{column:f(n.column),present:!1,table:f(n.table)}},ge=async(t,e,n,r)=>{const s=b(e);if(s===void 0)return!1;const o=f(s.table);return n.has(o)||r.stale.has(o)?!1:r.present.get(o)?.get(f(s.column))??await me(t,s.table,s.column)},ye=(t,e,n)=>{for(const r of e){const s=t.present.get(r.table)??new Map;s.set(r.column,r.present),t.present.set(r.table,s)}for(const r of n)t.stale.add(r)},Ae=(t,e)=>{if(K(e))throw new h("VALIDATION_ERROR",`${t.name} is transaction control (BEGIN/COMMIT/END/ROLLBACK/SAVEPOINT/RELEASE). Each file already runs atomically with its tracking row in one batch(); remove it.`);if(M(e.statementText))throw new h("VALIDATION_ERROR",`${t.name} changes foreign-key enforcement (PRAGMA foreign_keys). A migration file may not; remove it.`)},Te=(t,e)=>{const n=b(t);return n===void 0||e===void 0?void 0:z(e,n.table,n.column)},$e=(t,e,n)=>{const r=Re(t);r!==void 0&&e.push(r),P(t)===void 0&&U(t,n)},_e=(t,e)=>{const n=Te(t,e);return n===void 0?[t]:[t,n]},x=async(t,e,n,r,s=B())=>{const o=[],i=[],l=[],a=[],u=new Set,m=new Set,E=[];let d=!1,y=0;for(;y<e.sql.length;){const w=q(e.sql,e.name,y,!0);if(y=w.end,w.code.replaceAll(/[\s;]/gu,"")==="")continue;n&&Ae(e,w);const{statementText:R}=w,C=H(w)!==void 0;if($e(R,E,m),C&&o.push(R),fe(w)||i.push(R),await ge(t,R,u,s)){a.push(R);continue}l.push(..._e(R,r)),d||=pe(R,C),U(R,u)}return ye(s,E,m),{destructive:o,replayUnsafe:d,rootOnly:i,runs:l,skipped:a,statements:l.filter(w=>typeof w=="string")}},Oe=t=>{const e=new Set;for(const n of t){if(!j.test(n.name))throw new h("VALIDATION_ERROR",`migration file name "${n.name}" must be a plain *.sql file name`);if(e.has(n.name))throw new h("VALIDATION_ERROR",`migration file "${n.name}" was sent more than once`);e.add(n.name)}},Ie=async(t,e)=>{if(e){if((await t.drizzle.all(A.raw(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '${_}'`))).length===0)return{fresh:!0,recorded:new Map}}else await t.drizzle.run(A.raw(W));const n=await t.drizzle.all(A.raw(`SELECT name, sha256, written_by FROM ${_}`));return{fresh:!n.some(r=>r.written_by==="root"),recorded:new Map(n.map(r=>[r.name,{sha256:r.sha256,writtenBy:r.written_by}]))}},D=(t,e,n,r)=>({entry:{destructive:[],name:t.name,rootOnly:[],skipped:[],state:n,statements:[]},file:t,hash:e,...r===void 0?{}:{renamedFrom:r},replayUnsafe:!1}),Ne=(t,e)=>{const n=new Map;for(const[r,s]of t)!e.has(r)&&s.writtenBy==="root"&&n.set(s.sha256,r);return n},Le=async(t,e,n,r)=>{const s=await Promise.all(e.map(async a=>({file:a,hash:await V(X(a.sql))}))),o=Ne(n,new Set(e.map(a=>a.name))),i=B(),l=[];for(const{file:a,hash:u}of s){const m=n.get(a.name);if(m!==void 0){l.push(D(a,u,m.sha256===u?"applied":"changed"));continue}const E=o.get(u);if(E!==void 0){l.push(D(a,u,"changed",E));continue}const d=await x(t,a,r,void 0,i);l.push({entry:{destructive:d.destructive,name:a.name,rootOnly:d.rootOnly,skipped:d.skipped,state:"pending",statements:d.statements},file:a,hash:u,replayUnsafe:d.replayUnsafe})}return l},k=t=>{const e=new Map,n=[];for(const r of t.filter(s=>s.entry.state==="pending")){const s=e.get(r.hash);s===void 0?e.set(r.hash,r):n.push([s,r])}return n},Se=t=>{const e=k(t);if(e.length===0)return;const n=e.map(([r,s])=>`${s.entry.name} repeats ${r.entry.name}`).join("; ");throw new h("VALIDATION_ERROR",`${n}. Identical SQL would run once per name. Delete the extra file, or change its SQL.`)},be=t=>{const e=t.filter(o=>o.entry.state==="changed");if(e.length===0)return;const n=e.filter(o=>o.renamedFrom!==void 0),r=e.filter(o=>o.renamedFrom===void 0),s=[];if(r.length>0){const o=r.map(i=>i.entry.name).join(", ");s.push(`${o} ${r.length===1?"was":"were"} already applied from different SQL. Revert the edit and put the change in a new file.`)}if(n.length>0){const o=n.map(i=>`${i.entry.name} (applied as ${String(i.renamedFrom)})`).join(", ");s.push(`${o} ${n.length===1?"was":"were"} renamed. Rename it back: an applied file is never run again under a new name.`)}throw new h("MIGRATION_DRIFT",`${s.join(" ")} An applied file is never run again.`)},Ce=t=>t.statements.filter(e=>t.destructive.includes(e)||F(e)),De=/^(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/iu,ve=(t,e,n)=>{const r=t.filter(a=>a.entry.state==="pending");if(e.baseline===!0||e.baselineThrough!==void 0)return e.additiveOnly===!0?r.map(a=>a.entry.name):[];const o=a=>n&&a.replayUnsafe||e.additiveOnly===!0&&a.entry.rootOnly.length>0||a.entry.statements.some(u=>De.test(O(u))||M(u)),i=r.filter(a=>o(a)).map(a=>a.entry.name),l=k(t).flat().map(a=>a.entry.name);return[...new Set([...i,...l])]},Me=(t,e,n)=>{const r=t.filter(i=>i.entry.state==="pending");if(n){const i=r.filter(l=>l.replayUnsafe);if(i.length>0){const l=i.flatMap(a=>Ce(a.entry).map(u=>`${a.entry.name}: ${S(u)}`));throw new h("MIGRATION_DESTRUCTIVE",`no SQL migration file is recorded on this database, so these statements are refused. They drop, replace or write rows, and may already have run by hand or predate this tracking:
|
|
2
|
+
${l.join(`
|
|
3
|
+
`)}
|
|
4
|
+
Record the files that already ran with \`migrate apply --baseline-through <last file that ran>\`, then run the new ones.`)}return}const s=r.filter(i=>i.entry.destructive.length>0);if(s.length===0||e)return;const o=s.flatMap(i=>i.entry.destructive.map(l=>`${i.entry.name}: ${S(l)}`));throw new h("MIGRATION_DESTRUCTIVE",`these files drop, rename, truncate or replace data and have not run yet. Re-run with --allow-destructive to apply them:
|
|
5
|
+
${o.join(`
|
|
6
|
+
`)}`)},Ue=(t,e)=>{if(!e)return;const n=t.filter(s=>s.entry.state==="pending"&&s.entry.rootOnly.length>0);if(n.length===0)return;const r=n.flatMap(s=>s.entry.rootOnly.map(o=>`${s.entry.name}: ${S(o)}`));throw new h("MIGRATION_ROOT_REQUIRED",`these files run statements that a migrations-scoped token may not run (only CREATE TABLE, a CREATE INDEX that is not UNIQUE, and ADD COLUMN). Run them with the root admin token:
|
|
7
|
+
${r.join(`
|
|
8
|
+
`)}`)},Fe=async(t,e)=>(await t.drizzle.all(A.raw(`SELECT sha256, baselined FROM ${_} WHERE name = '${e}'`)))[0],G=async(t,e,n,r,s)=>{const o=s.origin==="baselined"?1:0,l=[t.drizzle.run(A.raw(`INSERT INTO ${_} (name, sha256, applied_at, baselined, written_by) VALUES ('${e.name}', '${n}', ${String(Date.now())}, ${String(o)}, '${s.writtenBy}')`)),...r.map(a=>t.drizzle.run(typeof a=="string"?A.raw(a):a))];try{return await t.batch(l),"ran"}catch(a){const u=a instanceof Error?a.message:String(a);if(!Y.test(u))throw new h("VALIDATION_ERROR",`${e.name} failed and was rolled back, so none of its statements took effect: ${u}`,{cause:a});const m=await Fe(t,e.name);if(m?.sha256===n){if(s.origin==="applied"&&m.baselined===1)throw new h("CONFLICT",`${e.name} was recorded as a baseline by a concurrent run, which records a file without running it. Its SQL did not run here, so this apply stopped; run it again to see the file's state.`,{cause:a});return"applied"}throw new h("MIGRATION_DRIFT",`${e.name} was recorded by a concurrent run from different SQL. An applied file is never run again: revert the edit and put the change in a new file.`,{cause:a})}},v=async(t,e,n)=>{const r=await x(t,e.file,!0,n.schema),s={origin:"applied",writtenBy:n.writtenBy};return{skipped:r.skipped,state:await G(t,e.file,e.hash,r.runs,s),statements:r.statements}},Be=async(t,e,n)=>{try{return await v(t,e,n)}catch(r){if(!(r instanceof Error)||!Z.test(r.message))throw r;return v(t,e,n)}},Pe=(t,e)=>{if(e.baseline===!0&&e.baselineThrough!==void 0)throw new h("VALIDATION_ERROR","pass either baseline or baselineThrough, not both");if(e.baselineThrough===void 0)return t.length-1;const n=t.findIndex(r=>r.name===e.baselineThrough);if(n===-1)throw new h("VALIDATION_ERROR",`baselineThrough names "${e.baselineThrough}", which is not among the files sent`);return n},xe=async(t,e,n)=>{for(const[r,s]of e.entries())if(s.entry.state==="pending"&&r<=n){const o={origin:"baselined",writtenBy:"root"};s.entry.state=await G(t,s.file,s.hash,[],o)==="ran"?"baselined":"applied"}},Xe=async(t,e,n={})=>{Oe(e);const r=n.baseline===!0||n.baselineThrough!==void 0,s=Pe(e,n),o=new Q(t),i=n.dryRun===!0,{fresh:l,recorded:a}=await Ie(o,i),u=n.additiveOnly===!0?"migrations":"root",m={schema:n.schema,writtenBy:u},E=await Le(o,e,a,!i&&!r);if(i)return{files:E.map(d=>d.entry),refused:ve(E,n,l)};if(be(E),r&&n.additiveOnly===!0)throw new h("MIGRATION_ROOT_REQUIRED","a baseline records files as applied without running them, so only the root admin token may run one");if(r)return await xe(o,E,s),{files:E.map(d=>d.entry)};Se(E),Ue(E,n.additiveOnly===!0),Me(E,n.confirmDestructive===!0,l);for(const d of E)if(d.entry.state==="pending"){const y=await Be(o,d,m);d.entry.skipped=y.skipped,d.entry.statements=y.statements,d.entry.state=y.state}return{files:E.map(d=>d.entry)}};export{Xe as applySqlMigrationFiles};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{backfillSqlSearchIndexes as r,createSqlCtxDb as o,readSqlCdcChanges as i,runSqlAggregateMigrations as c,runSqlCdcMigration as s,runSqlGlobalTableMigrations as l,runSqlRankMigrations as g,runSqlSearchMigrations as D,sweepSqlCdcRetention as S}from"@lunora/sql-store";import{createSqlCtxDb as w,decodeGlobalRow as G}from"@lunora/sql-store";import n from"./sqliteDialect-B_3JNtdq.mjs";const b=e=>o({...e,dialect:n}),q=(e,t)=>l(e,t,n),u=(e,t)=>c(e,t,n),M=(e,t)=>g(e,t,n),x=(e,t)=>D(e,t,n),h=(e,t)=>r(e,t,n),p=e=>s(e,n),f=(e,t={})=>i(e,t,n),m=(e,t,a)=>S(e,n,t,a);export{h as backfillD1SearchIndexes,b as createD1CtxDb,w as createSqlCtxDb,G as decodeGlobalRow,f as readD1CdcChanges,u as runD1AggregateMigrations,p as runD1CdcMigration,q as runD1GlobalTableMigrations,M as runD1RankMigrations,x as runD1SearchMigrations,m as sweepD1CdcRetention};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s="lunora",i="d1_query",c=new Set(["delete","insert","select","update"]),a=/\b(?:from|into|update)\s+["`[]?(?<table>[a-z_][\w$]*)/iu,u=/^\s*(?<verb>[a-z]+)/iu,d=o=>a.exec(o)?.groups?.table?.toLowerCase(),w=o=>{const t=u.exec(o)?.groups?.verb?.toLowerCase()??"",r=d(o);return c.has(t)?`${t}:${r??"unknown"}`:r===void 0?"other":`other:${r}`},n=(o,e)=>{const t=o?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0},E=o=>{const e=n(o,"rows_read"),t=n(o,"rows_written");if(e===void 0&&t===void 0)return;const r=n(o,"duration");return{...r===void 0?{}:{durationMs:r},rowsRead:e??0,rowsWritten:t??0}},b=(o,e)=>{const t=E(e);if(t===void 0)return;const r=JSON.stringify({durationMs:t.durationMs,rowsRead:t.rowsRead,rowsWritten:t.rowsWritten,source:s,tag:w(o),type:i});console.log(r)};export{w as d1QueryTag,b as emitD1QueryCost,E as readD1QueryCost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{exportSqlGlobalRows as e,importSqlGlobalRows as s}from"@lunora/sql-store";import{selectGlobalTables as c}from"@lunora/sql-store";import r from"./sqliteDialect-B_3JNtdq.mjs";const m=(o,l,t)=>e(o,l,r,t),b=(o,l,t)=>s(o,l,r,t);export{m as exportGlobalRows,b as importGlobalRows,c as selectGlobalTables};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{facetSqlGlobalColumn as t,listSqlGlobalTables as b,readSqlGlobalTablePage as s}from"@lunora/sql-store";import e from"./sqliteDialect-B_3JNtdq.mjs";const i=(l,a)=>b(l,a,e),m=(l,a,o)=>s(l,a,e,o),G=(l,a,o)=>t(l,a,e,o);export{G as facetGlobalColumn,i as listGlobalTables,m as readGlobalTablePage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=e=>`"${e.replaceAll('"','""')}"`;export{t as quoteIdentifier};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{renderSql as t}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{MAX_D1_TABLE_COLUMNS as a,sqlAffinityForKind as n}from"../dialect.mjs";const s=/unique constraint failed/iu,m={companionTypes:{autoincrementPrimaryKey:"INTEGER PRIMARY KEY AUTOINCREMENT",integer:"INTEGER",key:"TEXT",real:"REAL",text:"TEXT"},columnType:n,frameworkColumns:()=>[{name:"id",type:"TEXT PRIMARY KEY"},{name:"_creationTime",type:"REAL NOT NULL"}],isUniqueViolation:e=>e instanceof Error&&s.test(e.message),maxTableColumns:a,name:"sqlite",render:e=>t("sqlite",e),searchBackfillHint:"call backfillD1SearchIndexes with the store's exec from a host-side admin path",supportsFts5:!0,supportsReturning:!0,tableExists:e=>i`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${e}`};export{m as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/d1",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.240",
|
|
4
4
|
"description": "D1 adapter for Lunora .global() tables, wrapping the Sessions API for read-your-writes",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
],
|
|
15
15
|
"homepage": "https://lunora.sh",
|
|
16
16
|
"bugs": "https://github.com/anolilab/lunora/issues",
|
|
17
|
-
"license": "
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
18
|
"author": {
|
|
19
19
|
"name": "Daniel Bannert",
|
|
20
20
|
"email": "d.bannert@anolilab.de"
|
|
@@ -50,10 +50,12 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/
|
|
54
|
-
"@lunora/
|
|
55
|
-
"@lunora/
|
|
56
|
-
"
|
|
53
|
+
"@lunora/errors": ">=1.0.0-alpha.89 <2.0.0-0",
|
|
54
|
+
"@lunora/platform": "^1.0.0-alpha.83",
|
|
55
|
+
"@lunora/shard-engine": "^1.0.0-alpha.202",
|
|
56
|
+
"@lunora/sql-store": "^1.0.0-alpha.239",
|
|
57
|
+
"@lunora/wire": "1.0.0-alpha.6",
|
|
58
|
+
"drizzle-orm": "1.0.0-rc.5"
|
|
57
59
|
},
|
|
58
60
|
"engines": {
|
|
59
61
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
import { drizzle } from 'drizzle-orm/d1';
|
|
2
|
-
|
|
3
|
-
const STMT_CACHE_CAPACITY = 256;
|
|
4
|
-
const D1_FIRST_UNCONSTRAINED = "first-unconstrained";
|
|
5
|
-
class D1Session {
|
|
6
|
-
session;
|
|
7
|
-
/** See {@link D1Client.stmtCache}. Scoped per session. */
|
|
8
|
-
stmtCache = /* @__PURE__ */ new Map();
|
|
9
|
-
constructor(session) {
|
|
10
|
-
this.session = session;
|
|
11
|
-
}
|
|
12
|
-
prepare(sql) {
|
|
13
|
-
const cached = this.stmtCache.get(sql);
|
|
14
|
-
if (cached) {
|
|
15
|
-
this.stmtCache.delete(sql);
|
|
16
|
-
this.stmtCache.set(sql, cached);
|
|
17
|
-
return cached;
|
|
18
|
-
}
|
|
19
|
-
const stmt = this.session.prepare(sql);
|
|
20
|
-
if (this.stmtCache.size >= STMT_CACHE_CAPACITY) {
|
|
21
|
-
const oldest = this.stmtCache.keys().next().value;
|
|
22
|
-
if (oldest !== void 0) {
|
|
23
|
-
this.stmtCache.delete(oldest);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
this.stmtCache.set(sql, stmt);
|
|
27
|
-
return stmt;
|
|
28
|
-
}
|
|
29
|
-
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T types the result rows for the caller and is forwarded to the prepared statement.
|
|
30
|
-
async run(sql, ...binds) {
|
|
31
|
-
return this.prepare(sql).bind(...binds).run();
|
|
32
|
-
}
|
|
33
|
-
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T types the result rows for the caller and is forwarded to the prepared statement.
|
|
34
|
-
async all(sql, ...binds) {
|
|
35
|
-
return this.prepare(sql).bind(...binds).all();
|
|
36
|
-
}
|
|
37
|
-
async first(sql, ...binds) {
|
|
38
|
-
return this.prepare(sql).bind(...binds).first();
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Returns the most recent bookmark known to the session, or `undefined`
|
|
42
|
-
* when D1 has not issued one yet.
|
|
43
|
-
*/
|
|
44
|
-
getBookmark() {
|
|
45
|
-
return this.session.getBookmark() ?? void 0;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
class D1Client {
|
|
49
|
-
db;
|
|
50
|
-
/**
|
|
51
|
-
* SQL string -> prepared statement. Prepared statements are reusable in
|
|
52
|
-
* D1; preparing the same SQL twice forces the worker to round-trip the
|
|
53
|
-
* statement plan. Caching is per-instance so unit-test isolation holds.
|
|
54
|
-
* Bounded to {@link STMT_CACHE_CAPACITY} via LRU eviction.
|
|
55
|
-
*/
|
|
56
|
-
stmtCache = /* @__PURE__ */ new Map();
|
|
57
|
-
/**
|
|
58
|
-
* Lazily-built drizzle handle over the bare binding. Memoised so a single
|
|
59
|
-
* `D1Client` reuses the same dialect/session machinery across calls.
|
|
60
|
-
*/
|
|
61
|
-
drizzleHandle;
|
|
62
|
-
constructor(database) {
|
|
63
|
-
this.db = database;
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Open a Sessions-API scoped session. Pass the bookmark forwarded by
|
|
67
|
-
* the client to opt into read-your-writes consistency.
|
|
68
|
-
*
|
|
69
|
-
* With no bookmark this is the first request of a session — there is no
|
|
70
|
-
* prior write to read, so we open with the explicit `"first-unconstrained"`
|
|
71
|
-
* constraint (Cloudflare's lowest-latency default: the first read may serve
|
|
72
|
-
* from any replica). Read-your-writes for sequenced requests still flows
|
|
73
|
-
* through the forwarded bookmark; a caller needing a strongly-consistent
|
|
74
|
-
* very-first read should pass `"first-primary"` as the bookmark instead.
|
|
75
|
-
*/
|
|
76
|
-
withSession(bookmark) {
|
|
77
|
-
const session = this.db.withSession(bookmark ?? D1_FIRST_UNCONSTRAINED);
|
|
78
|
-
return new D1Session(session);
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Prepare a statement, reusing a cached one when the SQL text matches.
|
|
82
|
-
* `bind()` on a prepared statement returns a new bound statement and
|
|
83
|
-
* leaves the underlying prepared plan reusable, so cache hits are safe
|
|
84
|
-
* even when the previous caller already called `.bind(...).run()`.
|
|
85
|
-
*/
|
|
86
|
-
prepare(sql) {
|
|
87
|
-
const cached = this.stmtCache.get(sql);
|
|
88
|
-
if (cached) {
|
|
89
|
-
this.stmtCache.delete(sql);
|
|
90
|
-
this.stmtCache.set(sql, cached);
|
|
91
|
-
return cached;
|
|
92
|
-
}
|
|
93
|
-
const stmt = this.db.prepare(sql);
|
|
94
|
-
if (this.stmtCache.size >= STMT_CACHE_CAPACITY) {
|
|
95
|
-
const oldest = this.stmtCache.keys().next().value;
|
|
96
|
-
if (oldest !== void 0) {
|
|
97
|
-
this.stmtCache.delete(oldest);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
this.stmtCache.set(sql, stmt);
|
|
101
|
-
return stmt;
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Drizzle handle over the bare `env.DB` binding. Used for typed queries
|
|
105
|
-
* against generated `sqliteTable` schemas; does **not** participate in the
|
|
106
|
-
* D1 Sessions API (no bookmark pinning). For bookmark-scoped reads, use
|
|
107
|
-
* {@link drizzleSession} instead.
|
|
108
|
-
*/
|
|
109
|
-
get drizzle() {
|
|
110
|
-
if (this.drizzleHandle) {
|
|
111
|
-
return this.drizzleHandle;
|
|
112
|
-
}
|
|
113
|
-
this.drizzleHandle = drizzle(this.db, { logger: false });
|
|
114
|
-
return this.drizzleHandle;
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Drizzle handle scoped to a D1 Sessions-API session. The bookmark, when
|
|
118
|
-
* supplied, opts into read-your-writes consistency for follow-up reads on
|
|
119
|
-
* the same session.
|
|
120
|
-
*
|
|
121
|
-
* A `D1DatabaseSession` exposes the same `prepare` / `batch` surface
|
|
122
|
-
* drizzle calls into, so a single `unknown` cast lets us treat the session
|
|
123
|
-
* as a `D1Database` for driver-construction purposes.
|
|
124
|
-
*/
|
|
125
|
-
drizzleSession(bookmark) {
|
|
126
|
-
const session = this.db.withSession(bookmark ?? D1_FIRST_UNCONSTRAINED);
|
|
127
|
-
return drizzle(session, { logger: false });
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Atomic batch over the drizzle d1 driver. Mirrors `db.batch([...])`
|
|
131
|
-
* exactly; exposed on the client so callers don't need to hold a drizzle
|
|
132
|
-
* handle just to run a typed batch.
|
|
133
|
-
*/
|
|
134
|
-
async batch(items) {
|
|
135
|
-
return this.drizzle.batch(items);
|
|
136
|
-
}
|
|
137
|
-
/** Direct access to the underlying binding (advanced use only). */
|
|
138
|
-
get raw() {
|
|
139
|
-
return this.db;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
export { D1Client, D1Session };
|
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
import { LunoraError } from '@lunora/errors';
|
|
2
|
-
import { sql } from 'drizzle-orm';
|
|
3
|
-
import { D1Client } from './D1Client-DA3flo1o.mjs';
|
|
4
|
-
|
|
5
|
-
const TRACKING_TABLE_NAME = "__drizzle_migrations";
|
|
6
|
-
const TRACKING_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${TRACKING_TABLE_NAME} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL, created_at NUMERIC)`;
|
|
7
|
-
const WHITESPACE_RE = /\s/u;
|
|
8
|
-
const TRAILING_SEMICOLON_RE = /;\s*$/u;
|
|
9
|
-
const SHA256_HEX_RE = /^[0-9a-f]{64}$/u;
|
|
10
|
-
const assertSingleStatement = (migration) => {
|
|
11
|
-
const text = migration.sql;
|
|
12
|
-
let inSingle = false;
|
|
13
|
-
let inDouble = false;
|
|
14
|
-
let inLineComment = false;
|
|
15
|
-
let inBlockComment = false;
|
|
16
|
-
let seenStatement = false;
|
|
17
|
-
for (let index = 0; index < text.length; index += 1) {
|
|
18
|
-
const character = text[index];
|
|
19
|
-
const next = text[index + 1];
|
|
20
|
-
if (inLineComment) {
|
|
21
|
-
if (character === "\n") {
|
|
22
|
-
inLineComment = false;
|
|
23
|
-
}
|
|
24
|
-
continue;
|
|
25
|
-
}
|
|
26
|
-
if (inBlockComment) {
|
|
27
|
-
if (character === "*" && next === "/") {
|
|
28
|
-
inBlockComment = false;
|
|
29
|
-
index += 1;
|
|
30
|
-
}
|
|
31
|
-
continue;
|
|
32
|
-
}
|
|
33
|
-
if (inSingle) {
|
|
34
|
-
if (character === "'") {
|
|
35
|
-
if (next === "'") {
|
|
36
|
-
index += 1;
|
|
37
|
-
} else {
|
|
38
|
-
inSingle = false;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
continue;
|
|
42
|
-
}
|
|
43
|
-
if (inDouble) {
|
|
44
|
-
if (character === '"') {
|
|
45
|
-
if (next === '"') {
|
|
46
|
-
index += 1;
|
|
47
|
-
} else {
|
|
48
|
-
inDouble = false;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
continue;
|
|
52
|
-
}
|
|
53
|
-
if (character === "'") {
|
|
54
|
-
inSingle = true;
|
|
55
|
-
continue;
|
|
56
|
-
}
|
|
57
|
-
if (character === '"') {
|
|
58
|
-
inDouble = true;
|
|
59
|
-
continue;
|
|
60
|
-
}
|
|
61
|
-
if (character === "-" && next === "-") {
|
|
62
|
-
inLineComment = true;
|
|
63
|
-
index += 1;
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
if (character === "/" && next === "*") {
|
|
67
|
-
inBlockComment = true;
|
|
68
|
-
index += 1;
|
|
69
|
-
continue;
|
|
70
|
-
}
|
|
71
|
-
if (character === ";") {
|
|
72
|
-
seenStatement = true;
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
if (seenStatement && character !== void 0 && !WHITESPACE_RE.test(character)) {
|
|
76
|
-
throw new LunoraError(
|
|
77
|
-
"INTERNAL",
|
|
78
|
-
`Migration "${migration.name}" (v${String(migration.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`
|
|
79
|
-
);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
};
|
|
83
|
-
const hashMigration = async (text) => {
|
|
84
|
-
const bytes = new TextEncoder().encode(text);
|
|
85
|
-
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
86
|
-
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
87
|
-
};
|
|
88
|
-
class MigrationRunner {
|
|
89
|
-
client;
|
|
90
|
-
migrations;
|
|
91
|
-
/**
|
|
92
|
-
* Accepts either a {@link D1Client} (preferred — gets typed batches +
|
|
93
|
-
* drizzle handle for free) or a raw `D1DatabaseLike` binding (wrapped on
|
|
94
|
-
* the caller's behalf so existing `@lunora/cli` callers keep working).
|
|
95
|
-
*/
|
|
96
|
-
constructor(database, migrations) {
|
|
97
|
-
this.client = database instanceof D1Client ? database : new D1Client(database);
|
|
98
|
-
this.migrations = [...migrations].toSorted((a, b) => a.version - b.version);
|
|
99
|
-
this.assertUniqueVersions();
|
|
100
|
-
this.assertUniqueSql();
|
|
101
|
-
}
|
|
102
|
-
async run() {
|
|
103
|
-
await this.client.drizzle.run(sql.raw(TRACKING_TABLE_DDL));
|
|
104
|
-
const appliedRows = await this.client.drizzle.all(sql.raw(`SELECT hash FROM ${TRACKING_TABLE_NAME}`));
|
|
105
|
-
const appliedHashes = new Set(appliedRows.map((row) => row.hash));
|
|
106
|
-
const applied = [];
|
|
107
|
-
const skipped = [];
|
|
108
|
-
const hashes = await Promise.all(this.migrations.map(async (migration) => hashMigration(migration.sql)));
|
|
109
|
-
for (const [index, migration] of this.migrations.entries()) {
|
|
110
|
-
const hash = hashes[index];
|
|
111
|
-
if (appliedHashes.has(hash)) {
|
|
112
|
-
skipped.push({ name: migration.name, version: migration.version });
|
|
113
|
-
continue;
|
|
114
|
-
}
|
|
115
|
-
await this.applyOne(migration, hash);
|
|
116
|
-
applied.push({ name: migration.name, version: migration.version });
|
|
117
|
-
}
|
|
118
|
-
return { applied, skipped };
|
|
119
|
-
}
|
|
120
|
-
async applyOne(migration, hash) {
|
|
121
|
-
assertSingleStatement(migration);
|
|
122
|
-
const statementText = migration.sql.replace(TRAILING_SEMICOLON_RE, "").trim();
|
|
123
|
-
if (!SHA256_HEX_RE.test(hash)) {
|
|
124
|
-
throw new LunoraError("INTERNAL", `migration "${migration.name}" produced a non-hex hash; refusing to inline into SQL`);
|
|
125
|
-
}
|
|
126
|
-
const trackingInsertSql = `INSERT INTO ${TRACKING_TABLE_NAME} (hash, created_at) VALUES ('${hash}', ${String(Date.now())})`;
|
|
127
|
-
const items = [this.client.drizzle.run(sql.raw(statementText)), this.client.drizzle.run(sql.raw(trackingInsertSql))];
|
|
128
|
-
await this.client.batch(items);
|
|
129
|
-
}
|
|
130
|
-
assertUniqueVersions() {
|
|
131
|
-
const seen = /* @__PURE__ */ new Set();
|
|
132
|
-
for (const m of this.migrations) {
|
|
133
|
-
if (seen.has(m.version)) {
|
|
134
|
-
throw new LunoraError("INTERNAL", `Duplicate migration version ${String(m.version)}`);
|
|
135
|
-
}
|
|
136
|
-
seen.add(m.version);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
assertUniqueSql() {
|
|
140
|
-
const seen = /* @__PURE__ */ new Map();
|
|
141
|
-
for (const m of this.migrations) {
|
|
142
|
-
const previousVersion = seen.get(m.sql);
|
|
143
|
-
if (previousVersion !== void 0) {
|
|
144
|
-
throw new LunoraError(
|
|
145
|
-
"INTERNAL",
|
|
146
|
-
`Migrations ${String(previousVersion)} and ${String(m.version)} have identical SQL — bump the content, not just the version.`
|
|
147
|
-
);
|
|
148
|
-
}
|
|
149
|
-
seen.set(m.sql, m.version);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
export { MigrationRunner };
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { createSqlCtxDb, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, trimSqlCdcChanges } from '@lunora/sql-store';
|
|
2
|
-
export { createSqlCtxDb, decodeGlobalRow } from '@lunora/sql-store';
|
|
3
|
-
import sqliteDialect from './sqliteDialect-DqYnHPuu.mjs';
|
|
4
|
-
|
|
5
|
-
const createD1ContextDatabase = (options) => createSqlCtxDb({ ...options, dialect: sqliteDialect });
|
|
6
|
-
const runD1GlobalTableMigrations = (exec, schema) => runSqlGlobalTableMigrations(exec, schema, sqliteDialect);
|
|
7
|
-
const runD1AggregateMigrations = (exec, schema) => runSqlAggregateMigrations(exec, schema, sqliteDialect);
|
|
8
|
-
const runD1RankMigrations = (exec, schema) => runSqlRankMigrations(exec, schema, sqliteDialect);
|
|
9
|
-
const runD1SearchMigrations = (exec, schema) => runSqlSearchMigrations(exec, schema, sqliteDialect);
|
|
10
|
-
const runD1CdcMigration = (exec) => runSqlCdcMigration(exec, sqliteDialect);
|
|
11
|
-
const readD1CdcChanges = (exec, options = {}) => readSqlCdcChanges(exec, options, sqliteDialect);
|
|
12
|
-
const trimD1CdcChanges = (exec, throughSeq) => trimSqlCdcChanges(exec, throughSeq, sqliteDialect);
|
|
13
|
-
|
|
14
|
-
export { createD1ContextDatabase as createD1CtxDb, readD1CdcChanges, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, trimD1CdcChanges };
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { toErrorBody } from '@lunora/errors';
|
|
2
|
-
import { quoteIdentifier } from './quoteIdentifier-B-ZeSe1V.mjs';
|
|
3
|
-
import { decodeGlobalRow } from '@lunora/sql-store';
|
|
4
|
-
|
|
5
|
-
const DEFAULT_BATCH_SIZE = 200;
|
|
6
|
-
const selectGlobalTables = (schema, requested) => {
|
|
7
|
-
const isGlobal = (table) => schema.tables[table]?.shardMode?.kind === "global";
|
|
8
|
-
if (requested && requested.length > 0) {
|
|
9
|
-
return requested.filter((name) => isGlobal(name));
|
|
10
|
-
}
|
|
11
|
-
return Object.keys(schema.tables).filter((name) => isGlobal(name));
|
|
12
|
-
};
|
|
13
|
-
const decodeRow = (schema, table, row) => {
|
|
14
|
-
const definition = schema.tables[table];
|
|
15
|
-
if (!definition) {
|
|
16
|
-
return { _creationTime: row["_creationTime"], _id: row["id"] };
|
|
17
|
-
}
|
|
18
|
-
return decodeGlobalRow(definition, row);
|
|
19
|
-
};
|
|
20
|
-
const exportGlobalRows = async function* (exec, schema, args) {
|
|
21
|
-
const tables = selectGlobalTables(schema, args.tables);
|
|
22
|
-
const batchSize = args.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
23
|
-
for (const table of tables) {
|
|
24
|
-
let offset = 0;
|
|
25
|
-
let hasMore = true;
|
|
26
|
-
while (hasMore) {
|
|
27
|
-
const rows = await exec.all(`SELECT * FROM ${quoteIdentifier(table)} LIMIT ? OFFSET ?`, [batchSize, offset]);
|
|
28
|
-
for (const row of rows) {
|
|
29
|
-
yield { doc: decodeRow(schema, table, row), table };
|
|
30
|
-
}
|
|
31
|
-
hasMore = rows.length === batchSize;
|
|
32
|
-
offset += rows.length;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
const validateRow = (schema, table, document) => {
|
|
37
|
-
const definition = schema.tables[table];
|
|
38
|
-
if (!definition) {
|
|
39
|
-
return `unknown table: ${table}`;
|
|
40
|
-
}
|
|
41
|
-
for (const [field, validator] of Object.entries(definition.shape)) {
|
|
42
|
-
const candidate = document[field];
|
|
43
|
-
const optional = validator.kind === "optional";
|
|
44
|
-
if (candidate === void 0 && optional) {
|
|
45
|
-
continue;
|
|
46
|
-
}
|
|
47
|
-
const parser = validator.parse;
|
|
48
|
-
if (typeof parser !== "function") {
|
|
49
|
-
continue;
|
|
50
|
-
}
|
|
51
|
-
try {
|
|
52
|
-
parser(candidate);
|
|
53
|
-
} catch (error) {
|
|
54
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
55
|
-
return `field "${field}": ${message}`;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return void 0;
|
|
59
|
-
};
|
|
60
|
-
const explicitIdConflicts = async (writer, exec, table, explicitId) => {
|
|
61
|
-
try {
|
|
62
|
-
if (exec) {
|
|
63
|
-
const probe = await exec.all(`SELECT 1 AS hit FROM ${quoteIdentifier(table)} WHERE "id" = ? LIMIT 1`, [explicitId]);
|
|
64
|
-
return probe.length > 0;
|
|
65
|
-
}
|
|
66
|
-
const existing = await writer.get(explicitId);
|
|
67
|
-
return existing !== null;
|
|
68
|
-
} catch {
|
|
69
|
-
return false;
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
const importOneRow = async (writer, schema, args, row, line) => {
|
|
73
|
-
const { doc, table } = row;
|
|
74
|
-
if (schema.tables[table]?.shardMode?.kind !== "global") {
|
|
75
|
-
return { kind: "skip" };
|
|
76
|
-
}
|
|
77
|
-
if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
|
|
78
|
-
return { error: { code: "BAD_ROW", line, message: "row is missing or malformed `doc`", table }, kind: "error" };
|
|
79
|
-
}
|
|
80
|
-
const failure = validateRow(schema, table, doc);
|
|
81
|
-
if (failure !== void 0) {
|
|
82
|
-
return { error: { code: "VALIDATION_ERROR", line, message: failure, table }, kind: "error" };
|
|
83
|
-
}
|
|
84
|
-
const explicitId = typeof doc["_id"] === "string" ? doc["_id"] : void 0;
|
|
85
|
-
if (explicitId !== void 0 && await explicitIdConflicts(writer, args.exec, table, explicitId)) {
|
|
86
|
-
return { kind: "conflict" };
|
|
87
|
-
}
|
|
88
|
-
try {
|
|
89
|
-
await writer.insert(table, doc, { allowExplicitId: true });
|
|
90
|
-
return { inserted: table, kind: "inserted" };
|
|
91
|
-
} catch (error) {
|
|
92
|
-
const { body } = toErrorBody(error, { fallbackCode: "INSERT_FAILED" });
|
|
93
|
-
return { error: { code: body.code, line, message: body.message, table }, kind: "error" };
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
const importGlobalRows = async (writer, schema, args) => {
|
|
97
|
-
const errors = [];
|
|
98
|
-
const inserted = {};
|
|
99
|
-
let conflicts = 0;
|
|
100
|
-
let line = (args.startLine ?? 1) - 1;
|
|
101
|
-
for (const row of args.rows) {
|
|
102
|
-
line += 1;
|
|
103
|
-
const outcome = await importOneRow(writer, schema, args, row, line);
|
|
104
|
-
switch (outcome.kind) {
|
|
105
|
-
case "conflict": {
|
|
106
|
-
conflicts += 1;
|
|
107
|
-
break;
|
|
108
|
-
}
|
|
109
|
-
case "error": {
|
|
110
|
-
errors.push(outcome.error);
|
|
111
|
-
break;
|
|
112
|
-
}
|
|
113
|
-
case "inserted": {
|
|
114
|
-
inserted[outcome.inserted] = (inserted[outcome.inserted] ?? 0) + 1;
|
|
115
|
-
break;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
return { conflicts, errors, inserted };
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
export { exportGlobalRows, importGlobalRows, selectGlobalTables };
|