@lunora/d1 1.0.0-alpha.144 → 1.0.0-alpha.146
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 +29 -4
- package/dist/index.d.ts +29 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/MigrationRunner-DADTo9Q8.mjs +5 -0
- package/dist/packem_shared/{facetGlobalColumn-DLvqXVk_.mjs → facetGlobalColumn-CQpfkWoa.mjs} +1 -1
- package/package.json +4 -4
- package/dist/packem_shared/MigrationRunner-BGcgKW27.mjs +0 -2
package/dist/index.d.mts
CHANGED
|
@@ -361,10 +361,16 @@ interface MigrationRunnerResult {
|
|
|
361
361
|
}
|
|
362
362
|
/**
|
|
363
363
|
* Sequentially applies pending migrations against a D1 database via the
|
|
364
|
-
* drizzle-orm/d1 driver
|
|
365
|
-
*
|
|
366
|
-
*
|
|
367
|
-
*
|
|
364
|
+
* drizzle-orm/d1 driver, recording each one's `version` and SHA-256 in
|
|
365
|
+
* `__drizzle_migrations`.
|
|
366
|
+
*
|
|
367
|
+
* A migration is skipped when its VERSION is recorded, never by its text alone.
|
|
368
|
+
* Deduplicating by hash re-applied any migration whose text changed after it
|
|
369
|
+
* ran — a comment, a whitespace fix, a CRLF checkout — so a non-idempotent one
|
|
370
|
+
* (`SET balance = balance * 100`) ran twice. A recorded version whose hash no
|
|
371
|
+
* longer matches is refused as `MIGRATION_DRIFT` instead: the runner cannot
|
|
372
|
+
* tell a harmless edit from a changed migration, and running either again is
|
|
373
|
+
* the one outcome that is never right.
|
|
368
374
|
*/
|
|
369
375
|
declare class MigrationRunner {
|
|
370
376
|
private readonly client;
|
|
@@ -376,6 +382,25 @@ declare class MigrationRunner {
|
|
|
376
382
|
*/
|
|
377
383
|
constructor(database: D1Client | D1DatabaseLike, migrations: Migration[]);
|
|
378
384
|
run(): Promise<MigrationRunnerResult>;
|
|
385
|
+
/** Does the tracking table carry the `version` column yet? One catalog read. */
|
|
386
|
+
private hasVersionColumn;
|
|
387
|
+
/**
|
|
388
|
+
* Create the tracking table, or bring one written before `version` existed
|
|
389
|
+
* up to the current shape.
|
|
390
|
+
*
|
|
391
|
+
* Two runners can upgrade the same table at once (parallel deploys): both
|
|
392
|
+
* see no column, and the second `ADD COLUMN` fails with "duplicate column
|
|
393
|
+
* name". That failure is only accepted once a re-read shows the column
|
|
394
|
+
* really is there — any other failure of the `ALTER` still surfaces.
|
|
395
|
+
*/
|
|
396
|
+
private ensureTrackingTable;
|
|
397
|
+
/**
|
|
398
|
+
* Read the tracking rows, first giving every row recorded before versions
|
|
399
|
+
* were tracked the version whose SQL it hashed — the only link to a version
|
|
400
|
+
* such a row has. A row whose hash matches no current migration stays
|
|
401
|
+
* unversioned, and {@link run} refuses to guess around it.
|
|
402
|
+
*/
|
|
403
|
+
private readTrackingRows;
|
|
379
404
|
private applyOne;
|
|
380
405
|
private assertUniqueVersions;
|
|
381
406
|
private assertUniqueSql;
|
package/dist/index.d.ts
CHANGED
|
@@ -361,10 +361,16 @@ interface MigrationRunnerResult {
|
|
|
361
361
|
}
|
|
362
362
|
/**
|
|
363
363
|
* Sequentially applies pending migrations against a D1 database via the
|
|
364
|
-
* drizzle-orm/d1 driver
|
|
365
|
-
*
|
|
366
|
-
*
|
|
367
|
-
*
|
|
364
|
+
* drizzle-orm/d1 driver, recording each one's `version` and SHA-256 in
|
|
365
|
+
* `__drizzle_migrations`.
|
|
366
|
+
*
|
|
367
|
+
* A migration is skipped when its VERSION is recorded, never by its text alone.
|
|
368
|
+
* Deduplicating by hash re-applied any migration whose text changed after it
|
|
369
|
+
* ran — a comment, a whitespace fix, a CRLF checkout — so a non-idempotent one
|
|
370
|
+
* (`SET balance = balance * 100`) ran twice. A recorded version whose hash no
|
|
371
|
+
* longer matches is refused as `MIGRATION_DRIFT` instead: the runner cannot
|
|
372
|
+
* tell a harmless edit from a changed migration, and running either again is
|
|
373
|
+
* the one outcome that is never right.
|
|
368
374
|
*/
|
|
369
375
|
declare class MigrationRunner {
|
|
370
376
|
private readonly client;
|
|
@@ -376,6 +382,25 @@ declare class MigrationRunner {
|
|
|
376
382
|
*/
|
|
377
383
|
constructor(database: D1Client | D1DatabaseLike, migrations: Migration[]);
|
|
378
384
|
run(): Promise<MigrationRunnerResult>;
|
|
385
|
+
/** Does the tracking table carry the `version` column yet? One catalog read. */
|
|
386
|
+
private hasVersionColumn;
|
|
387
|
+
/**
|
|
388
|
+
* Create the tracking table, or bring one written before `version` existed
|
|
389
|
+
* up to the current shape.
|
|
390
|
+
*
|
|
391
|
+
* Two runners can upgrade the same table at once (parallel deploys): both
|
|
392
|
+
* see no column, and the second `ADD COLUMN` fails with "duplicate column
|
|
393
|
+
* name". That failure is only accepted once a re-read shows the column
|
|
394
|
+
* really is there — any other failure of the `ALTER` still surfaces.
|
|
395
|
+
*/
|
|
396
|
+
private ensureTrackingTable;
|
|
397
|
+
/**
|
|
398
|
+
* Read the tracking rows, first giving every row recorded before versions
|
|
399
|
+
* were tracked the version whose SQL it hashed — the only link to a version
|
|
400
|
+
* such a row has. A row whose hash matches no current migration stays
|
|
401
|
+
* unversioned, and {@link run} refuses to guess around it.
|
|
402
|
+
*/
|
|
403
|
+
private readTrackingRows;
|
|
379
404
|
private applyOne;
|
|
380
405
|
private assertUniqueVersions;
|
|
381
406
|
private assertUniqueSql;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportGlobalRows as o,importGlobalRows as t,selectGlobalTables as a}from"./packem_shared/exportGlobalRows-B2zTH0eN.mjs";import{D1Client as i,D1Session as n}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as D,createD1CtxDb as p,readD1CdcChanges as x,runD1AggregateMigrations as b,runD1CdcMigration as g,runD1GlobalTableMigrations as m,runD1RankMigrations as c,runD1SearchMigrations as f,sweepD1CdcRetention as u}from"./packem_shared/backfillD1SearchIndexes-Dcv_bQOk.mjs";import{facetGlobalColumn as d,listGlobalTables as G,readGlobalTablePage as T}from"./packem_shared/facetGlobalColumn-
|
|
1
|
+
import{exportGlobalRows as o,importGlobalRows as t,selectGlobalTables as a}from"./packem_shared/exportGlobalRows-B2zTH0eN.mjs";import{D1Client as i,D1Session as n}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as D,createD1CtxDb as p,readD1CdcChanges as x,runD1AggregateMigrations as b,runD1CdcMigration as g,runD1GlobalTableMigrations as m,runD1RankMigrations as c,runD1SearchMigrations as f,sweepD1CdcRetention as u}from"./packem_shared/backfillD1SearchIndexes-Dcv_bQOk.mjs";import{facetGlobalColumn as d,listGlobalTables as G,readGlobalTablePage as T}from"./packem_shared/facetGlobalColumn-CQpfkWoa.mjs";import{MigrationRunner as M}from"./packem_shared/MigrationRunner-DADTo9Q8.mjs";import{d1QueryTag as h,emitD1QueryCost as w,readD1QueryCost as S}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as Q,isTransientD1Error as k,retryingExec as q,withD1Retry as A}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{default as P}from"./packem_shared/sqliteDialect-Bjdkna-G.mjs";import{applyCdcChanges as v}from"@lunora/shard-engine";import{createSqlCtxDb as B}from"@lunora/sql-store";export{i as D1Client,n as D1Session,Q as D1TimeoutError,M as MigrationRunner,v as applyCdcChanges,D as backfillD1SearchIndexes,p as createD1CtxDb,B as createSqlCtxDb,h as d1QueryTag,w as emitD1QueryCost,o as exportGlobalRows,d as facetGlobalColumn,t as importGlobalRows,k as isTransientD1Error,G as listGlobalTables,x as readD1CdcChanges,S as readD1QueryCost,T as readGlobalTablePage,q as retryingExec,b as runD1AggregateMigrations,g as runD1CdcMigration,m as runD1GlobalTableMigrations,c as runD1RankMigrations,f as runD1SearchMigrations,a as selectGlobalTables,P as sqliteDialect,u as sweepD1CdcRetention,A as withD1Retry};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as w}from"drizzle-orm";import{D1Client as S}from"./D1Client-CzS0Qfa6.mjs";const d="__drizzle_migrations",A=`CREATE TABLE IF NOT EXISTS ${d} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC, version INTEGER)`,$=`CREATE UNIQUE INDEX IF NOT EXISTS ${d}_version ON ${d} (version)`,p=/\s/u,_=/[$\w]/u,T=String.raw`(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)`,y=/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/u,L=new RegExp(String.raw`^CREATE${T}+(?:TEMP${T}+|TEMPORARY${T}+)?TRIGGER\b`,"iu"),z=/^[0-9a-f]{64}$/u,C=new RegExp(String.raw`UNIQUE constraint failed:\s*${d}\.(?:hash|version)`,"iu"),U=o=>{const e=o.sql,n=L.test(e.slice(y.exec(e)?.[0].length??0));let s=!1,a=!1,h=!1,f=!1,t=!1,c=!1,i,l="",E=!1,v=!1;for(let u=0;u<e.length;u+=1){const r=e[u],m=e[u+1];if(t){r===`
|
|
2
|
+
`&&(t=!1);continue}if(c){r==="*"&&m==="/"&&(c=!1,u+=1);continue}if(s){r==="'"&&(m==="'"?u+=1:s=!1);continue}if(a){r==='"'&&(m==='"'?u+=1:a=!1);continue}if(h){r==="]"&&(h=!1);continue}if(f){r==="`"&&(m==="`"?u+=1:f=!1);continue}if(r==="-"&&m==="-"){t=!0,u+=1;continue}if(r==="/"&&m==="*"){c=!0,u+=1;continue}if(i!==void 0){if(r!==void 0&&!p.test(r))throw new g("INTERNAL",`Migration "${o.name}" (v${String(o.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);continue}if(n&&r!==void 0){if(_.test(r)){l+=r;continue}const R=l.toUpperCase();l="",R!==""?(E=v&&R==="END",v=!1):r!==";"&&!p.test(r)&&(E=!1,v=!1)}if(r==="'"){s=!0;continue}if(r==='"'){a=!0;continue}if(r==="["){h=!0;continue}if(r==="`"){f=!0;continue}if(r===";"){if(n&&!E){v=!0;continue}i=u}}return i},I=async o=>{const e=new TextEncoder().encode(o),n=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(n)].map(s=>s.toString(16).padStart(2,"0")).join("")},M=/^\uFEFF/u,D=o=>{let e=o.length;for(;e>0&&o[e-1]===`
|
|
3
|
+
`;)e-=1;return o.slice(0,e)},N=o=>D(o.replace(M,"").replaceAll(`\r
|
|
4
|
+
`,`
|
|
5
|
+
`)),O=async o=>({normalized:await I(N(o)),raw:await I(o)}),H=(o,e)=>o===e?.normalized||o===e?.raw;class q{client;migrations;constructor(e,n){this.client=e instanceof S?e:new S(e),this.migrations=[...n].toSorted((s,a)=>s.version-a.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.ensureTrackingTable();const e=await Promise.all(this.migrations.map(async i=>O(i.sql))),n=await this.readTrackingRows(e),s=new Map(n.filter(i=>i.version!==null).map(i=>[i.version,i.hash])),a=i=>String(e[i]?.normalized),h=this.migrations.filter((i,l)=>{const E=s.get(i.version);if(E!==void 0&&!H(E,e[l]))throw new g("MIGRATION_DRIFT",`Migration "${i.name}" (v${String(i.version)}) was already applied from different SQL (recorded sha256 ${E}, now ${a(l)}). 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 ${d} SET hash = '${a(l)}' WHERE version = ${String(i.version)};`);return E===void 0}),f=n.filter(i=>i.version===null);if(h.length>0&&f.length>0)throw new g("MIGRATION_DRIFT",`${d} holds ${String(f.length)} row(s) recorded before versions were tracked whose SQL matches no current migration (id ${f.map(i=>String(i.id)).join(", ")}), and ${h.map(i=>`v${String(i.version)}`).join(", ")} ${h.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 ${d} SET version = <n> WHERE id = <id>; for a migration that no longer exists, any version no current migration uses), then run again.`);const t=[],c=[];for(const[i,l]of this.migrations.entries()){const E=a(i);if(!h.includes(l)){c.push({name:l.name,version:l.version});continue}await this.applyOne(l,E)?t.push({name:l.name,version:l.version}):c.push({name:l.name,version:l.version})}return{applied:t,skipped:c}}async hasVersionColumn(){return(await this.client.drizzle.all(w.raw(`SELECT name FROM pragma_table_info('${d}') WHERE name = 'version'`))).length>0}async ensureTrackingTable(){if(await this.client.drizzle.run(w.raw(A)),!await this.hasVersionColumn())try{await this.client.drizzle.run(w.raw(`ALTER TABLE ${d} ADD COLUMN version INTEGER`))}catch(e){if(!await this.hasVersionColumn())throw e}await this.client.drizzle.run(w.raw($))}async readTrackingRows(e){const n=w.raw(`SELECT id, hash, version FROM ${d} ORDER BY id`),s=await this.client.drizzle.all(n),a=new Map(this.migrations.flatMap((t,c)=>[[String(e[c]?.raw),t.version],[String(e[c]?.normalized),t.version]])),h=new Set(s.map(t=>t.version).filter(t=>t!==null));let f=!1;for(const t of s){const c=t.version===null?a.get(t.hash):void 0;c===void 0||h.has(c)||(await this.client.drizzle.run(w`UPDATE ${w.raw(d)} SET version = ${c} WHERE id = ${t.id} AND version IS NULL`),h.add(c),f=!0)}return f?await this.client.drizzle.all(n):s}async applyOne(e,n){const s=U(e),a=(s===void 0?e.sql:e.sql.slice(0,s)).trim();if(!z.test(n))throw new g("INTERNAL",`migration "${e.name}" produced a non-hex hash; refusing to inline into SQL`);const h=`INSERT INTO ${d} (hash, created_at, version) VALUES ('${n}', ${String(Date.now())}, ${String(e.version)})`,f=[this.client.drizzle.run(w.raw(a)),this.client.drizzle.run(w.raw(h))];try{await this.client.batch(f)}catch(t){if(C.test(t instanceof Error?t.message:String(t)))return!1;throw t}return!0}assertUniqueVersions(){const e=new Set;for(const n of this.migrations){if(!Number.isSafeInteger(n.version))throw new g("INTERNAL",`Migration "${n.name}" has version ${String(n.version)}; a version must be an integer`);if(e.has(n.version))throw new g("INTERNAL",`Duplicate migration version ${String(n.version)}`);e.add(n.version)}}assertUniqueSql(){const e=new Map;for(const n of this.migrations){const s=N(n.sql),a=e.get(s);if(a!==void 0)throw new g("INTERNAL",`Migrations ${String(a)} and ${String(n.version)} have identical SQL — bump the content, not just the version.`);e.set(s,n.version)}}}export{q as MigrationRunner,d as TRACKING_TABLE_NAME};
|
package/dist/packem_shared/{facetGlobalColumn-DLvqXVk_.mjs → facetGlobalColumn-CQpfkWoa.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as N}from"@lunora/errors";import{isInternalTableName as L}from"@lunora/shard-engine";import{sqliteDecode as G,effectiveColumnKind as D,decodeGlobalRow as F,sqliteEncode as M}from"@lunora/sql-store";import{n as _,e as A}from"./wire-codec-nGFLAn3r.mjs";import{runD1GlobalTableMigrations as R}from"./backfillD1SearchIndexes-Dcv_bQOk.mjs";import{TRACKING_TABLE_NAME as U}from"./MigrationRunner-
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{isInternalTableName as L}from"@lunora/shard-engine";import{sqliteDecode as G,effectiveColumnKind as D,decodeGlobalRow as F,sqliteEncode as M}from"@lunora/sql-store";import{n as _,e as A}from"./wire-codec-nGFLAn3r.mjs";import{runD1GlobalTableMigrations as R}from"./backfillD1SearchIndexes-Dcv_bQOk.mjs";import{TRACKING_TABLE_NAME as U}from"./MigrationRunner-DADTo9Q8.mjs";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";const P=50,q=500,B=30,k=200,S=(t,o,n)=>Math.min(Math.max(t,o),n),K=t=>L(t)||t.startsWith("d1_")||t===U,v=/password|secret|token|hash|salt|credential/iu,u=(t,o)=>{const n=t.tables[o];return n?.shardMode?.kind==="global"?n:void 0},O=async t=>(await t.all("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",[])).map(n=>String(n.name)).filter(n=>!K(n)),$=async(t,o,n)=>{if(await R(t,o),!(await O(t)).includes(n))throw new N("UNKNOWN_TABLE",`unknown table: ${n}`,{status:404})},g=async(t,o,n="",e=[])=>{const r=await t.all(`SELECT COUNT(*) AS c FROM ${o}${n}`,e);return Number(r[0]?.c??0)},h=(t,o,n)=>u(t,o)!==void 0&&n==="_id"?"id":n,y=(t,o,n)=>{const e=u(t,o)?.shape[n];return e===void 0?void 0:D(e)},W=/^-?\d+$/u,Y=(t,o)=>{if(o!=="bigint")return M(t);const n=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return M(n!==void 0&&W.test(n)?BigInt(n):t,o)},C=(t,o,n,e)=>{const r=[],a=[];for(const s of e??[]){if(!n.includes(s.column))throw new N("UNKNOWN_COLUMN",`unknown column: ${s.column}`,{status:404});if(u(t,o)===void 0&&v.test(s.column))throw new N("FORBIDDEN",`cannot filter on a redacted column: ${s.column}`,{status:403});const i=l(h(t,o,s.column));s.value===null||s.value===void 0?r.push(`${i} IS NULL`):(r.push(`${i} = ?`),a.push(Y(s.value,y(t,o,s.column))))}return{params:a,where:r.length>0?` WHERE ${r.join(" AND ")}`:""}},j=(t,o,n)=>{const e=u(t,o);if(e)return F(e,n);const r={};for(const[a,s]of Object.entries(n))r[a]=s!=null&&v.test(a)?"•••":s;return r},I=async(t,o,n)=>{const e=u(o,n);return e?["_id","_creationTime",...Object.keys(e.shape)]:(await t.all(`PRAGMA table_info(${l(n)})`,[])).map(a=>String(a.name))},X=async(t,o,n)=>{if(u(o,n))return;const e=await t.all(`PRAGMA foreign_key_list(${l(n)})`,[]);if(e.length===0)return;const r={};for(const a of e){const s=String(a.from),i=String(a.table);r[s]??=i}return r},nt=async(t,o)=>{await R(t,o);const n=await O(t);return Promise.all(n.map(async e=>({name:e,rowCount:await g(t,l(e))})))},H=async(t,o,n,e)=>{if(u(o,n)!==void 0)return l("id");const a=(await t.all(`PRAGMA table_info(${l(n)})`,[])).filter(s=>Number(s.pk??0)>0);return a.length===1?l(String(a[0]?.name)):e.includes("id")?l("id"):"rowid"},ot=async(t,o,n)=>{const{table:e}=n;await $(t,o,e);const r=S(Math.trunc(n.limit??P),1,q),a=Math.max(0,Math.trunc(n.offset??0)),s=l(e),i=await I(t,o,e),{params:m,where:d}=C(o,e,i,n.filters),f=await g(t,s,d,m),w=await H(t,o,e,i),b=(await t.all(`SELECT * FROM ${s}${d} ORDER BY ${w} LIMIT ? OFFSET ?`,[...m,r,a])).map(E=>{const c=j(o,e,E);return _(c)?A(c):c}),T=await X(t,o,e);return T===void 0?{columns:i,rows:b,total:f}:{columns:i,refs:T,rows:b,total:f}},et=async(t,o,n)=>{const{column:e,table:r}=n;await $(t,o,r);const a=await I(t,o,r);if(!a.includes(e))throw new N("UNKNOWN_COLUMN",`unknown column: ${e}`,{status:404});const s=l(r),{params:i,where:m}=C(o,r,a,n.filters);if(u(o,r)===void 0&&v.test(e)){const c=await g(t,s,m,i);return{truncated:!1,values:c===0?[]:[{count:c,value:"•••"}]}}const d=S(Math.trunc(n.limit??B),1,k),f=l(h(o,r,e)),w=await t.all(`SELECT ${f} AS value, COUNT(*) AS count FROM ${s}${m} GROUP BY ${f} ORDER BY count DESC, ${f} ASC LIMIT ?`,[...i,d+1]),p=w.length>d,b=p?w.slice(0,d):w,T=y(o,r,e)==="bigint",E=b.map(c=>({count:Number(c.count),value:T?G(c.value,"bigint"):c.value}));return{truncated:p,values:_(E)?A(E):E}};export{et as facetGlobalColumn,nt as listGlobalTables,ot as readGlobalTablePage};
|
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.146",
|
|
4
4
|
"description": "D1 adapter for Lunora .global() tables, wrapping the Sessions API for read-your-writes",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -50,10 +50,10 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
53
|
+
"@lunora/errors": "1.0.0-alpha.46",
|
|
54
54
|
"@lunora/platform": "1.0.0-alpha.41",
|
|
55
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
56
|
-
"@lunora/sql-store": "1.0.0-alpha.
|
|
55
|
+
"@lunora/shard-engine": "1.0.0-alpha.95",
|
|
56
|
+
"@lunora/sql-store": "1.0.0-alpha.147",
|
|
57
57
|
"drizzle-orm": "^0.45.2"
|
|
58
58
|
},
|
|
59
59
|
"engines": {
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{D1Client as T}from"./D1Client-CzS0Qfa6.mjs";const p="__drizzle_migrations",I=`CREATE TABLE IF NOT EXISTS ${p} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC)`,A=/\s/u,N=/[$\w]/u,g=String.raw`(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)`,v=/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/u,_=new RegExp(String.raw`^CREATE${g}+(?:TEMP${g}+|TEMPORARY${g}+)?TRIGGER\b`,"iu"),L=/^[0-9a-f]{64}$/u,$=new RegExp(String.raw`UNIQUE constraint failed:\s*${p}\.hash`,"iu"),C=l=>{const e=l.sql,t=_.test(e.slice(v.exec(e)?.[0].length??0));let i=!1,o=!1,c=!1,r=!1,s=!1,f=!1,h,R="",S=!1,E=!1;for(let a=0;a<e.length;a+=1){const n=e[a],u=e[a+1];if(s){n===`
|
|
2
|
-
`&&(s=!1);continue}if(f){n==="*"&&u==="/"&&(f=!1,a+=1);continue}if(i){n==="'"&&(u==="'"?a+=1:i=!1);continue}if(o){n==='"'&&(u==='"'?a+=1:o=!1);continue}if(c){n==="]"&&(c=!1);continue}if(r){n==="`"&&(u==="`"?a+=1:r=!1);continue}if(n==="-"&&u==="-"){s=!0,a+=1;continue}if(n==="/"&&u==="*"){f=!0,a+=1;continue}if(h!==void 0){if(n!==void 0&&!A.test(n))throw new d("INTERNAL",`Migration "${l.name}" (v${String(l.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);continue}if(t&&n!==void 0){if(N.test(n)){R+=n;continue}const w=R.toUpperCase();R="",w!==""?(S=E&&w==="END",E=!1):n!==";"&&!A.test(n)&&(S=!1,E=!1)}if(n==="'"){i=!0;continue}if(n==='"'){o=!0;continue}if(n==="["){c=!0;continue}if(n==="`"){r=!0;continue}if(n===";"){if(t&&!S){E=!0;continue}h=a}}return h},U=async l=>{const e=new TextEncoder().encode(l),t=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(i=>i.toString(16).padStart(2,"0")).join("")};class M{client;migrations;constructor(e,t){this.client=e instanceof T?e:new T(e),this.migrations=[...t].toSorted((i,o)=>i.version-o.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.client.drizzle.run(m.raw(I));const e=await this.client.drizzle.all(m.raw(`SELECT hash FROM ${p}`)),t=new Set(e.map(r=>r.hash)),i=[],o=[],c=await Promise.all(this.migrations.map(async r=>U(r.sql)));for(const[r,s]of this.migrations.entries()){const f=c[r];if(t.has(f)){o.push({name:s.name,version:s.version});continue}await this.applyOne(s,f)?i.push({name:s.name,version:s.version}):o.push({name:s.name,version:s.version})}return{applied:i,skipped:o}}async applyOne(e,t){const i=C(e),o=(i===void 0?e.sql:e.sql.slice(0,i)).trim();if(!L.test(t))throw new d("INTERNAL",`migration "${e.name}" produced a non-hex hash; refusing to inline into SQL`);const c=`INSERT INTO ${p} (hash, created_at) VALUES ('${t}', ${String(Date.now())})`,r=[this.client.drizzle.run(m.raw(o)),this.client.drizzle.run(m.raw(c))];try{await this.client.batch(r)}catch(s){if($.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(e.has(t.version))throw new d("INTERNAL",`Duplicate migration version ${String(t.version)}`);e.add(t.version)}}assertUniqueSql(){const e=new Map;for(const t of this.migrations){const i=e.get(t.sql);if(i!==void 0)throw new d("INTERNAL",`Migrations ${String(i)} and ${String(t.version)} have identical SQL — bump the content, not just the version.`);e.set(t.sql,t.version)}}}export{M as MigrationRunner,p as TRACKING_TABLE_NAME};
|