@lunora/d1 1.0.0-alpha.236 → 1.0.0-alpha.238

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SchemaLike, DatabaseWriterLike } from '@lunora/shard-engine';
2
2
  export { applyCdcChanges } from '@lunora/shard-engine';
3
- import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, FacetGlobalColumnOptions, GlobalFacetResult, GlobalTableInfo, ReadGlobalTablePageOptions, GlobalTablePage, SqlDialect } from '@lunora/sql-store';
3
+ import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, ImportError, FacetGlobalColumnOptions, GlobalFacetResult, GlobalTableInfo, ReadGlobalTablePageOptions, GlobalTablePage, SqlDialect } from '@lunora/sql-store';
4
4
  export { type SqlCtxExec as D1Exec, type ExportGlobalArgs, type FacetGlobalColumnOptions, type ExportRow as GlobalExportRow, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type ImportError as GlobalImportError, type ImportResult as GlobalImportResult, type GlobalTableInfo, type GlobalTablePage, type ImportGlobalArgs, type ReadGlobalTablePageOptions, type SqlCtxDbOptions, type SqlCtxExec, createSqlCtxDb, selectGlobalTables } from '@lunora/sql-store';
5
5
  import { D1DatabaseLike, D1SessionLike, D1PreparedStatementLike } from '@lunora/platform';
6
6
  export type { D1DatabaseLike, D1PreparedStatementLike, D1SessionLike } from '@lunora/platform';
@@ -164,6 +164,54 @@ declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
164
164
  * they can all reason about, and the lease is what stops them racing.
165
165
  */
166
166
  declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
167
+ /**
168
+ * What a staged commit reports. Its own shape, not `ImportResult`: a replace counts
169
+ * rows written per table (overwrites included) and rows pruned per table, which the
170
+ * runtime session totals across planes.
171
+ */
172
+ interface StagedCommitResult {
173
+ conflicts: number;
174
+ /** Rows pruned per table because the snapshot did not hold them. */
175
+ deleted: Record<string, number>;
176
+ errors: ImportError[];
177
+ inserted: Record<string, number>;
178
+ }
179
+ /** A staged-replace failure the caller maps to its HTTP status. */
180
+ declare class GlobalImportStagingError extends Error {
181
+ readonly code: string;
182
+ constructor(code: string, message: string);
183
+ }
184
+ interface StageGlobalArgs {
185
+ /** The session's generation (see `@lunora/shard-engine`'s `import-staging`): rows of another one are refused. */
186
+ generation: string;
187
+ rows: ReadonlyArray<ExportRow>;
188
+ session: string;
189
+ startLine?: number;
190
+ /** The session's `.global()` replace scope. */
191
+ tables: ReadonlyArray<string>;
192
+ }
193
+ /**
194
+ * Validate and stage one request's `.global()` rows. Any refused row stages none
195
+ * of them — the session is then never committed.
196
+ */
197
+ declare const stageGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: StageGlobalArgs, now?: number) => Promise<{
198
+ errors: ImportError[];
199
+ staged: Record<string, number>;
200
+ }>;
201
+ /**
202
+ * Swap the session's staged rows in for `tables`: overwrite or insert each, then
203
+ * prune. Retry-safe — see the module doc for what holds on a failure. `staged`
204
+ * says whether the session staged any `.global()` row: a session that did must
205
+ * still hold them, one that did not empties the tables.
206
+ */
207
+ declare const commitStagedGlobalRows: (writer: DatabaseWriterLike, exec: SqlCtxExec, schema: SchemaLike, args: {
208
+ generation: string;
209
+ session: string;
210
+ staged: boolean;
211
+ tables: ReadonlyArray<string>;
212
+ }, now?: number) => Promise<StagedCommitResult>;
213
+ /** Forget a session of `generation`: its staged rows and its marker. Another generation's rows are left to their own expiry. */
214
+ declare const abortStagedGlobalRows: (exec: SqlCtxExec, session: string, generation: string) => Promise<void>;
167
215
  /** Every browsable D1 table with its row count (schema `.global()` tables provisioned first). */
168
216
  declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
169
217
  /** One page of a D1 table's rows, eq-filtered. */
@@ -433,4 +481,4 @@ declare const applySqlMigrationFiles: (database: D1DatabaseLike, files: Readonly
433
481
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
434
482
  */
435
483
  declare const sqliteDialect: SqlDialect;
436
- export { ALLOW_DESTRUCTIVE_MARKER, type ApplySqlMigrationOptions, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, type SqlMigrationEntry, type SqlMigrationFile, type SqlMigrationResult, type SqlMigrationState, applySqlMigrationFiles, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
484
+ export { ALLOW_DESTRUCTIVE_MARKER, type ApplySqlMigrationOptions, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, GlobalImportStagingError, type Migration, MigrationRunner, type MigrationRunnerResult, type SqlMigrationEntry, type SqlMigrationFile, type SqlMigrationResult, type SqlMigrationState, type StageGlobalArgs, type StagedCommitResult, abortStagedGlobalRows, applySqlMigrationFiles, backfillD1SearchIndexes, commitStagedGlobalRows, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, stageGlobalRows, sweepD1CdcRetention, withD1Retry };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SchemaLike, DatabaseWriterLike } from '@lunora/shard-engine';
2
2
  export { applyCdcChanges } from '@lunora/shard-engine';
3
- import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, FacetGlobalColumnOptions, GlobalFacetResult, GlobalTableInfo, ReadGlobalTablePageOptions, GlobalTablePage, SqlDialect } from '@lunora/sql-store';
3
+ import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, ImportError, FacetGlobalColumnOptions, GlobalFacetResult, GlobalTableInfo, ReadGlobalTablePageOptions, GlobalTablePage, SqlDialect } from '@lunora/sql-store';
4
4
  export { type SqlCtxExec as D1Exec, type ExportGlobalArgs, type FacetGlobalColumnOptions, type ExportRow as GlobalExportRow, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type ImportError as GlobalImportError, type ImportResult as GlobalImportResult, type GlobalTableInfo, type GlobalTablePage, type ImportGlobalArgs, type ReadGlobalTablePageOptions, type SqlCtxDbOptions, type SqlCtxExec, createSqlCtxDb, selectGlobalTables } from '@lunora/sql-store';
5
5
  import { D1DatabaseLike, D1SessionLike, D1PreparedStatementLike } from '@lunora/platform';
6
6
  export type { D1DatabaseLike, D1PreparedStatementLike, D1SessionLike } from '@lunora/platform';
@@ -164,6 +164,54 @@ declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
164
164
  * they can all reason about, and the lease is what stops them racing.
165
165
  */
166
166
  declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
167
+ /**
168
+ * What a staged commit reports. Its own shape, not `ImportResult`: a replace counts
169
+ * rows written per table (overwrites included) and rows pruned per table, which the
170
+ * runtime session totals across planes.
171
+ */
172
+ interface StagedCommitResult {
173
+ conflicts: number;
174
+ /** Rows pruned per table because the snapshot did not hold them. */
175
+ deleted: Record<string, number>;
176
+ errors: ImportError[];
177
+ inserted: Record<string, number>;
178
+ }
179
+ /** A staged-replace failure the caller maps to its HTTP status. */
180
+ declare class GlobalImportStagingError extends Error {
181
+ readonly code: string;
182
+ constructor(code: string, message: string);
183
+ }
184
+ interface StageGlobalArgs {
185
+ /** The session's generation (see `@lunora/shard-engine`'s `import-staging`): rows of another one are refused. */
186
+ generation: string;
187
+ rows: ReadonlyArray<ExportRow>;
188
+ session: string;
189
+ startLine?: number;
190
+ /** The session's `.global()` replace scope. */
191
+ tables: ReadonlyArray<string>;
192
+ }
193
+ /**
194
+ * Validate and stage one request's `.global()` rows. Any refused row stages none
195
+ * of them — the session is then never committed.
196
+ */
197
+ declare const stageGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: StageGlobalArgs, now?: number) => Promise<{
198
+ errors: ImportError[];
199
+ staged: Record<string, number>;
200
+ }>;
201
+ /**
202
+ * Swap the session's staged rows in for `tables`: overwrite or insert each, then
203
+ * prune. Retry-safe — see the module doc for what holds on a failure. `staged`
204
+ * says whether the session staged any `.global()` row: a session that did must
205
+ * still hold them, one that did not empties the tables.
206
+ */
207
+ declare const commitStagedGlobalRows: (writer: DatabaseWriterLike, exec: SqlCtxExec, schema: SchemaLike, args: {
208
+ generation: string;
209
+ session: string;
210
+ staged: boolean;
211
+ tables: ReadonlyArray<string>;
212
+ }, now?: number) => Promise<StagedCommitResult>;
213
+ /** Forget a session of `generation`: its staged rows and its marker. Another generation's rows are left to their own expiry. */
214
+ declare const abortStagedGlobalRows: (exec: SqlCtxExec, session: string, generation: string) => Promise<void>;
167
215
  /** Every browsable D1 table with its row count (schema `.global()` tables provisioned first). */
168
216
  declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
169
217
  /** One page of a D1 table's rows, eq-filtered. */
@@ -433,4 +481,4 @@ declare const applySqlMigrationFiles: (database: D1DatabaseLike, files: Readonly
433
481
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
434
482
  */
435
483
  declare const sqliteDialect: SqlDialect;
436
- export { ALLOW_DESTRUCTIVE_MARKER, type ApplySqlMigrationOptions, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, type SqlMigrationEntry, type SqlMigrationFile, type SqlMigrationResult, type SqlMigrationState, applySqlMigrationFiles, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
484
+ export { ALLOW_DESTRUCTIVE_MARKER, type ApplySqlMigrationOptions, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, GlobalImportStagingError, type Migration, MigrationRunner, type MigrationRunnerResult, type SqlMigrationEntry, type SqlMigrationFile, type SqlMigrationResult, type SqlMigrationState, type StageGlobalArgs, type StagedCommitResult, abortStagedGlobalRows, applySqlMigrationFiles, backfillD1SearchIndexes, commitStagedGlobalRows, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, stageGlobalRows, sweepD1CdcRetention, withD1Retry };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportGlobalRows as o,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 D,readD1CdcChanges as p,runD1AggregateMigrations as x,runD1CdcMigration as m,runD1GlobalTableMigrations as f,runD1RankMigrations as g,runD1SearchMigrations as b,sweepD1CdcRetention as c}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{facetGlobalColumn as u,listGlobalTables as d,readGlobalTablePage as R}from"./packem_shared/facetGlobalColumn-BqK1_P3S.mjs";import{MigrationRunner as M}from"./packem_shared/MigrationRunner-CD5zcqp6.mjs";import{d1QueryTag as G,emitD1QueryCost as E,readD1QueryCost as S}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as w,isTransientD1Error as q,retryingExec as A,withD1Retry as Q}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{applySqlMigrationFiles as I}from"./packem_shared/applySqlMigrationFiles-CUiRKrxP.mjs";import{default as _}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as K}from"@lunora/shard-engine";import{ALLOW_DESTRUCTIVE_MARKER as P}from"./packem_shared/ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{createSqlCtxDb as V,selectGlobalTables as W}from"@lunora/sql-store";export{P as ALLOW_DESTRUCTIVE_MARKER,l as D1Client,i as D1Session,w as D1TimeoutError,M as MigrationRunner,K as applyCdcChanges,I as applySqlMigrationFiles,s as backfillD1SearchIndexes,D as createD1CtxDb,V as createSqlCtxDb,G as d1QueryTag,E as emitD1QueryCost,o as exportGlobalRows,u as facetGlobalColumn,t as importGlobalRows,q as isTransientD1Error,d as listGlobalTables,p as readD1CdcChanges,S as readD1QueryCost,R as readGlobalTablePage,A as retryingExec,x as runD1AggregateMigrations,m as runD1CdcMigration,f as runD1GlobalTableMigrations,g as runD1RankMigrations,b as runD1SearchMigrations,W as selectGlobalTables,_ as sqliteDialect,c as sweepD1CdcRetention,Q as withD1Retry};
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-CHuhNZmR.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
+ import{toErrorBody as b}from"@lunora/errors";import{prepareGlobalImportRow as w}from"@lunora/sql-store";import{encodeWire as g,decodeWire as _}from"@lunora/wire";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";const d="__lunora_import_stage__",c="__lunora_import_session__",O=1440*60*1e3,S=200,h=(o,t,s)=>{const e=[],n=[];let l=(t.startLine??1)-1;for(const i of t.rows){l+=1;const r=i.line??l;if(!s.has(i.table)){e.push({code:"BAD_ROW",line:r,message:`table "${i.table}" is not in this replace import's tables`,table:i.table});continue}const a=w(o,i,r);a.kind==="settled"?a.outcome.kind==="error"&&e.push(a.outcome.error):a.kind==="delete"?e.push({code:"BAD_ROW",line:r,message:'a replace import does not take `op: "delete"` rows',table:i.table}):a.explicitId===void 0?e.push({code:"BAD_ROW",line:r,message:"a replace import row must carry its `_id`",table:a.table}):n.push({decoded:a.decoded,id:a.explicitId,line:r,table:a.table})}return{errors:e,ready:n}},A=async(o,t,s)=>(await o.all(`SELECT 1 FROM ${u(t)} WHERE id = ? LIMIT 1`,[s])).length>0,M=async(o,t,s)=>{try{if(await A(t,s.table,s.id)){const e={...s.decoded};delete e._id,await o.replace(s.table,s.id,e,{allowExplicitId:!0})}else await o.insert(s.table,s.decoded,{allowExplicitId:!0});return}catch(e){const{body:n}=b(e,{fallbackCode:"INSERT_FAILED"});return{code:n.code,line:s.line,message:n.message,table:s.table}}};class R extends Error{code;constructor(t,s){super(s),this.name="GlobalImportStagingError",this.code=t}}const I=async o=>{await o.run(`CREATE TABLE IF NOT EXISTS "${d}" (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 "${d}_by_session" ON "${d}" (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)`,[])},m=async(o,t)=>{if(o.batch){await o.batch(t);return}for(const{params:s,sql:e}of t)await o.run(e,s)},f=async(o,t)=>{await I(o),await m(o,[{params:[t],sql:`DELETE FROM "${d}" WHERE session IN (SELECT session FROM "${c}" WHERE expires_at < ? AND state IN ('staging', 'committed'))`},{params:[t],sql:`DELETE FROM "${c}" WHERE expires_at < ? AND state IN ('staging', 'committed')`}])},L=async(o,t,s)=>{const[e]=await o.all(`SELECT state, generation, result FROM "${c}" WHERE session = ?`,[t]);if(e===void 0)return;const n=String(e.state);if(n!=="staging"&&n!=="committed")throw new R("IMPORT_SESSION_CORRUPT",`import session "${t}" has an unreadable state in D1`);if(String(e.generation)!==s)throw new R("IMPORT_SESSION_STALE",`import session "${t}" in D1 belongs to an earlier session of the same id`);return typeof e.result=="string"?{generation:s,result:JSON.parse(e.result),state:n}:{generation:s,state:n}},H=async(o,t,s,e=Date.now())=>{if(await f(o,e),(await L(o,s.session,s.generation))?.state==="committed")throw new R("IMPORT_SESSION_COMMITTED",`import session "${s.session}" is already committed`);const l=new Set(s.tables.filter(E=>t.tables[E]?.shardMode?.kind==="global")),{errors:i,ready:r}=h(t,s,l);if(i.length>0)return{errors:i,staged:{}};const a={};return await m(o,[{params:[s.session,s.generation,e+O],sql:`INSERT INTO "${c}" (session, state, generation, expires_at) VALUES (?, 'staging', ?, ?) ON CONFLICT (session) DO UPDATE SET expires_at = excluded.expires_at`},...r.map(({decoded:E,id:T,line:p,table:N})=>(a[N]=(a[N]??0)+1,{params:[s.session,N,T,p,JSON.stringify(g(E))],sql:`INSERT INTO "${d}" (session, tbl, id, line, doc) VALUES (?, ?, ?, ?, ?)`}))]),{errors:[],staged:a}},D=async(o,t,s)=>{const e={};let n=0;for(;;){const l=await t.all(`SELECT seq, tbl, id, line, doc FROM "${d}" WHERE session = ? AND seq > ? ORDER BY seq LIMIT ?`,[s,n,S]),i=[];for(const r of l){const a=String(r.tbl),E=String(r.id),T=_(JSON.parse(String(r.doc))),p=await M(o,t,{decoded:T,id:E,line:Number(r.line),table:a});p===void 0?e[a]=(e[a]??0)+1:i.push(p)}if(i.length>0||l.length<S)return{errors:i,inserted:e};n=Number(l.at(-1)?.seq)}},$=async(o,t,s,e)=>{if((await t.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",[e])).length===0)return 0;let l=0;for(;;){const i=await t.all(`SELECT "id" FROM ${u(e)} WHERE "id" NOT IN (SELECT id FROM "${d}" WHERE session = ? AND tbl = ?) LIMIT ?`,[s,e,S]);for(const{id:r}of i)await o.delete(e,String(r),{hard:!0});if(l+=i.length,i.length<S)return l}},y=async(o,t)=>(await o.all(`SELECT 1 FROM "${d}" WHERE session = ? LIMIT 1`,[t])).length>0,U=async(o,t,s,e,n=Date.now())=>{await f(t,n);const l=await L(t,e.session,e.generation);if(l?.state==="committed"&&l.result!==void 0)return l.result;if(e.staged&&(l===void 0||!await y(t,e.session)))throw new R("IMPORT_SESSION_EXPIRED",`import session "${e.session}" has no staged .global() rows (expired, or aborted)`);const{errors:i,inserted:r}=await D(o,t,e.session);if(i.length>0)return{conflicts:0,deleted:{},errors:i,inserted:r};const a={};for(const T of e.tables.filter(p=>s.tables[p]?.shardMode?.kind==="global"))a[T]=await $(o,t,e.session,T);const E={conflicts:0,deleted:a,errors:[],inserted:r};return await m(t,[{params:[e.session,e.generation,n+O,JSON.stringify(E)],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 "${d}" WHERE session = ?`}]),E},X=async(o,t,s)=>{await I(o),await m(o,[{params:[t,t,s],sql:`DELETE FROM "${d}" WHERE session = ? AND EXISTS (SELECT 1 FROM "${c}" WHERE session = ? AND generation = ?)`},{params:[t,s],sql:`DELETE FROM "${c}" WHERE session = ? AND generation = ?`}])};export{R as GlobalImportStagingError,X as abortStagedGlobalRows,U as commitStagedGlobalRows,H as stageGlobalRows};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/d1",
3
- "version": "1.0.0-alpha.236",
3
+ "version": "1.0.0-alpha.238",
4
4
  "description": "D1 adapter for Lunora .global() tables, wrapping the Sessions API for read-your-writes",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -51,9 +51,10 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@lunora/errors": ">=1.0.0-alpha.89 <2.0.0-0",
54
- "@lunora/platform": "1.0.0-alpha.80",
55
- "@lunora/shard-engine": "^1.0.0-alpha.193",
56
- "@lunora/sql-store": "^1.0.0-alpha.236",
54
+ "@lunora/platform": "^1.0.0-alpha.81",
55
+ "@lunora/shard-engine": "^1.0.0-alpha.200",
56
+ "@lunora/sql-store": "^1.0.0-alpha.237",
57
+ "@lunora/wire": "1.0.0-alpha.6",
57
58
  "drizzle-orm": "1.0.0-rc.5"
58
59
  },
59
60
  "engines": {