durable-db 0.0.2 → 0.0.3
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/cli/index.d.ts
CHANGED
package/dist/db/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-jBv90-Pk.js";
|
|
2
|
-
import { _ as
|
|
3
|
-
export { Action, ActionConfig, ActionContext, ActionInfo, ArgsSchema, CamelCasePlugin, CompiledQuery, CreateKyselyOptions, DatabaseConfig, DatabaseDefinition, DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, DrizzleToKysely, InferArgs, Kysely, KyselyPlugin, Migration, MigrationAttemptInfo, Migrations, ParsedDatabaseFile, QueryResult, SchemaPlugin, SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
|
2
|
+
import { _ as Migrations, a as QueryResult, b as createKyselyFromSql, c as DateSerializePlugin, d as createDrizzlePlugins, f as dateSerializers, g as MigrationSchemaConflictError, h as MigrationAttemptInfo, i as KyselyPlugin, l as DrizzleDefaultsPlugin, m as Migration, n as CompiledQuery, o as studio, p as CreateKyselyOptions, r as Kysely, s as type, t as CamelCasePlugin, u as SchemaPlugin, v as SqlExecutor, y as SqliteDurableObject } from "../index-CU9edk9Q.js";
|
|
3
|
+
export { Action, ActionConfig, ActionContext, ActionInfo, ArgsSchema, CamelCasePlugin, CompiledQuery, CreateKyselyOptions, DatabaseConfig, DatabaseDefinition, DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, DrizzleToKysely, InferArgs, Kysely, KyselyPlugin, Migration, MigrationAttemptInfo, MigrationSchemaConflictError, Migrations, ParsedDatabaseFile, QueryResult, SchemaPlugin, SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
package/dist/db/index.js
CHANGED
|
@@ -394,6 +394,21 @@ function createKyselyFromSql(sqlStorage, options = {}) {
|
|
|
394
394
|
*/
|
|
395
395
|
const MAX_PITR_ATTEMPTS = 3;
|
|
396
396
|
/**
|
|
397
|
+
* Raised when a pending migration fails with "already exists": the storage
|
|
398
|
+
* holds schema objects the `__migrations` journal doesn't track. Common
|
|
399
|
+
* causes: migration files were renamed or regenerated after the storage was
|
|
400
|
+
* created, the storage was written by an older version of the database, or a
|
|
401
|
+
* previous attempt crashed partway through a chunk without PITR. Re-running
|
|
402
|
+
* can never succeed, so this carries recovery guidance instead of the raw
|
|
403
|
+
* SQLITE_ERROR.
|
|
404
|
+
*/
|
|
405
|
+
var MigrationSchemaConflictError = class extends Error {
|
|
406
|
+
constructor(message, options) {
|
|
407
|
+
super(message, options);
|
|
408
|
+
this.name = "MigrationSchemaConflictError";
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
/**
|
|
397
412
|
* Truncate a SQL statement for logging. Collapses whitespace so multi-line
|
|
398
413
|
* statements render on one log line.
|
|
399
414
|
*/
|
|
@@ -573,17 +588,24 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
573
588
|
this.sql.exec(`
|
|
574
589
|
UPDATE __migration_attempts SET last_error = ? WHERE id = 'current'
|
|
575
590
|
`, errorMessage);
|
|
576
|
-
|
|
577
|
-
const remaining = Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount);
|
|
578
|
-
const pendingNames = Array.from(new Set(pending.map((p) => p.name))).join(", ");
|
|
579
|
-
console.error(`[database] Migration failed (attempt ${attempts.attemptCount}/${MAX_PITR_ATTEMPTS + 1}, ${remaining} PITR-protected retries remaining). Restoring to pre-migration bookmark. Pending: ${pendingNames || "(none)"}.`, error);
|
|
591
|
+
let restoreScheduled = false;
|
|
580
592
|
try {
|
|
581
593
|
await this.ctx.storage.onNextSessionRestoreBookmark(bookmark);
|
|
582
|
-
|
|
594
|
+
restoreScheduled = true;
|
|
583
595
|
} catch (pitrErr) {
|
|
584
596
|
const pitrMessage = pitrErr instanceof Error ? pitrErr.message : String(pitrErr);
|
|
585
|
-
if (
|
|
586
|
-
|
|
597
|
+
if (/does not (?:implement|support) point-in-time recovery/i.test(pitrMessage)) {
|
|
598
|
+
this.pitrAvailable = false;
|
|
599
|
+
this.pitrUnavailableReason = pitrMessage;
|
|
600
|
+
debugMigrations("PITR restore unsupported by this storage backend; disabling PITR (%s)", pitrMessage);
|
|
601
|
+
} else console.error(`[database] PITR restore failed (${pitrMessage}). Propagating the original migration error instead so you can fix the root cause.`);
|
|
602
|
+
}
|
|
603
|
+
if (restoreScheduled) {
|
|
604
|
+
const attempts = this.getMigrationAttempts();
|
|
605
|
+
const remaining = Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount);
|
|
606
|
+
const pendingNames = Array.from(new Set(pending.map((p) => p.name))).join(", ");
|
|
607
|
+
console.error(`[database] Migration failed (attempt ${attempts.attemptCount}/${MAX_PITR_ATTEMPTS + 1}, ${remaining} PITR-protected retries remaining). Restoring to pre-migration bookmark. Pending: ${pendingNames || "(none)"}.`, error);
|
|
608
|
+
this.ctx.abort("Restoring to pre-migration bookmark");
|
|
587
609
|
}
|
|
588
610
|
}
|
|
589
611
|
throw error;
|
|
@@ -634,11 +656,30 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
634
656
|
} catch (error) {
|
|
635
657
|
const location = currentStatement !== null ? ` stmt ${currentIndex}: ${formatStatementForLog(currentStatement)}` : " (while recording chunk as applied)";
|
|
636
658
|
console.error(`[database] Migration chunk failed: ${name}[${chunkIndex}]${location}`, error);
|
|
637
|
-
throw error;
|
|
659
|
+
throw this.toSchemaConflictError(error, name, chunkIndex) ?? error;
|
|
638
660
|
}
|
|
639
661
|
}
|
|
640
662
|
}
|
|
641
663
|
/**
|
|
664
|
+
* Translate an "already exists" failure on a pending migration into a
|
|
665
|
+
* {@link MigrationSchemaConflictError}. A chunk is only executed when the
|
|
666
|
+
* journal has no row for it, so "already exists" means storage and journal
|
|
667
|
+
* disagree about what has been applied — retrying can never succeed, and
|
|
668
|
+
* the raw SQLITE_ERROR doesn't tell the user how to get unstuck.
|
|
669
|
+
* Returns null when the error isn't this case.
|
|
670
|
+
*/
|
|
671
|
+
toSchemaConflictError(error, name, chunkIndex) {
|
|
672
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
673
|
+
if (!/already exists/i.test(message)) return null;
|
|
674
|
+
let journalNames = [];
|
|
675
|
+
try {
|
|
676
|
+
journalNames = this.sql.exec("SELECT DISTINCT name FROM __migrations").toArray().map((row) => row.name);
|
|
677
|
+
} catch {}
|
|
678
|
+
const known = new Set(Object.keys(this.migrations));
|
|
679
|
+
const untracked = journalNames.filter((n) => !known.has(n));
|
|
680
|
+
return new MigrationSchemaConflictError(`Migration "${name}" (chunk ${chunkIndex}) tried to create a schema object that already exists in storage, but the __migrations journal has no record of this migration being applied. ${untracked.length > 0 ? `The journal records migrations this build doesn't know about (${untracked.join(", ")}), which usually means the migration files were renamed or regenerated after this database's storage was created.` : "This usually means the storage was created by migrations under different names (renamed or regenerated migration files), by an older version of this database, or that a previous attempt crashed partway through a chunk."} To recover in local dev, run \`db reset\` to rotate to a fresh database (add --purge-local-storage to also delete the orphaned instance data, or wipe .wrangler/state yourself). In production, restore the original migration names, or baseline the journal by inserting rows into __migrations for the migrations whose schema is already present. Original error: ${message}`, { cause: error });
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
642
683
|
* Manually restore the DO to a specific PITR bookmark.
|
|
643
684
|
* The DO will restart on next access with the restored state.
|
|
644
685
|
*/
|
|
@@ -757,4 +798,4 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
757
798
|
};
|
|
758
799
|
|
|
759
800
|
//#endregion
|
|
760
|
-
export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
|
801
|
+
export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
|
@@ -78,6 +78,18 @@ interface MigrationStatus {
|
|
|
78
78
|
*/
|
|
79
79
|
pitrAttemptsRemaining: number;
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Raised when a pending migration fails with "already exists": the storage
|
|
83
|
+
* holds schema objects the `__migrations` journal doesn't track. Common
|
|
84
|
+
* causes: migration files were renamed or regenerated after the storage was
|
|
85
|
+
* created, the storage was written by an older version of the database, or a
|
|
86
|
+
* previous attempt crashed partway through a chunk without PITR. Re-running
|
|
87
|
+
* can never succeed, so this carries recovery guidance instead of the raw
|
|
88
|
+
* SQLITE_ERROR.
|
|
89
|
+
*/
|
|
90
|
+
declare class MigrationSchemaConflictError extends Error {
|
|
91
|
+
constructor(message: string, options?: ErrorOptions);
|
|
92
|
+
}
|
|
81
93
|
/**
|
|
82
94
|
* Base class for SQLite Durable Objects with migration support
|
|
83
95
|
*
|
|
@@ -179,6 +191,15 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
|
|
|
179
191
|
* Apply a list of pending migration chunks.
|
|
180
192
|
*/
|
|
181
193
|
private applyMigrations;
|
|
194
|
+
/**
|
|
195
|
+
* Translate an "already exists" failure on a pending migration into a
|
|
196
|
+
* {@link MigrationSchemaConflictError}. A chunk is only executed when the
|
|
197
|
+
* journal has no row for it, so "already exists" means storage and journal
|
|
198
|
+
* disagree about what has been applied — retrying can never succeed, and
|
|
199
|
+
* the raw SQLITE_ERROR doesn't tell the user how to get unstuck.
|
|
200
|
+
* Returns null when the error isn't this case.
|
|
201
|
+
*/
|
|
202
|
+
private toSchemaConflictError;
|
|
182
203
|
/**
|
|
183
204
|
* Manually restore the DO to a specific PITR bookmark.
|
|
184
205
|
* The DO will restart on next access with the restored state.
|
|
@@ -325,4 +346,4 @@ declare class DateSerializePlugin implements KyselyPlugin {
|
|
|
325
346
|
*/
|
|
326
347
|
declare function createDrizzlePlugins(schema: Record<string, SQLiteTableWithColumns<any>>, camelCase?: boolean): KyselyPlugin[];
|
|
327
348
|
//#endregion
|
|
328
|
-
export {
|
|
349
|
+
export { Migrations as _, QueryResult$1 as a, createKyselyFromSql as b, DateSerializePlugin as c, createDrizzlePlugins as d, dateSerializers as f, MigrationSchemaConflictError as g, MigrationAttemptInfo as h, KyselyPlugin$1 as i, DrizzleDefaultsPlugin as l, Migration as m, CompiledQuery as n, studio as o, CreateKyselyOptions as p, Kysely$1 as r, type$1 as s, CamelCasePlugin$1 as t, SchemaPlugin as u, SqlExecutor as v, SqliteDurableObject as y };
|
package/dist/vite/durableDb.js
CHANGED
|
@@ -217,7 +217,8 @@ function checkWranglerConfig(projectRoot, databases) {
|
|
|
217
217
|
configPath,
|
|
218
218
|
missingBindings: [],
|
|
219
219
|
missingSqliteClasses: [],
|
|
220
|
-
ok: true
|
|
220
|
+
ok: true,
|
|
221
|
+
tomlOnly: !configPath && fs.existsSync(path.join(projectRoot, "wrangler.toml"))
|
|
221
222
|
};
|
|
222
223
|
let config = {};
|
|
223
224
|
if (configPath) try {
|
|
@@ -238,7 +239,7 @@ function checkWranglerConfig(projectRoot, databases) {
|
|
|
238
239
|
new_sqlite_classes: result.missingSqliteClasses
|
|
239
240
|
}] }
|
|
240
241
|
}, null, 2);
|
|
241
|
-
const hasToml =
|
|
242
|
+
const hasToml = result.tomlOnly;
|
|
242
243
|
const where = configPath ? path.basename(configPath) : hasToml ? "wrangler.toml (not supported — only wrangler.jsonc/json can be verified or patched)" : "wrangler.jsonc";
|
|
243
244
|
console.warn(`[durable-db] ${where} is missing Durable Object config for your database(s). Add ${hasToml ? "the equivalent of " : ""}this${configPath || hasToml ? "" : " to a new wrangler.jsonc"}:\n${snippet}\n` + (hasToml ? "" : `Or let the plugin write it for you: durableDb({ patchWranglerConfig: true })`));
|
|
244
245
|
}
|
|
@@ -752,9 +753,24 @@ var PluginState = class {
|
|
|
752
753
|
projectRoot = "";
|
|
753
754
|
config;
|
|
754
755
|
devServer = null;
|
|
756
|
+
selfDevStateWriteUntil = 0;
|
|
755
757
|
constructor(options) {
|
|
756
758
|
this.options = options;
|
|
757
759
|
}
|
|
760
|
+
/**
|
|
761
|
+
* Mark an imminent write to the dev cache made by the plugin itself
|
|
762
|
+
* (persisting a freshly minted epoch on first run). The cache watcher
|
|
763
|
+
* ignores events inside this window — without it, the plugin's own
|
|
764
|
+
* bootstrap write would trigger a full reload on the very first dev-server
|
|
765
|
+
* run, before any client (or the Cloudflare worker's hot channel
|
|
766
|
+
* WebSocket) is connected.
|
|
767
|
+
*/
|
|
768
|
+
markSelfDevStateWrite() {
|
|
769
|
+
this.selfDevStateWriteUntil = Date.now() + 1500;
|
|
770
|
+
}
|
|
771
|
+
isWithinSelfDevStateWriteWindow() {
|
|
772
|
+
return Date.now() <= this.selfDevStateWriteUntil;
|
|
773
|
+
}
|
|
758
774
|
registerDatabaseFile(filePath, dbName) {
|
|
759
775
|
const abs = path.normalize(filePath);
|
|
760
776
|
this.databaseFilePaths.set(abs, dbName);
|
|
@@ -809,7 +825,10 @@ var PluginState = class {
|
|
|
809
825
|
debugVite("Found %d database(s)", this.databases.size);
|
|
810
826
|
const databases = Array.from(this.databases.values());
|
|
811
827
|
if (this.options.patchWranglerConfig) patchWranglerConfig(this.projectRoot, databases);
|
|
812
|
-
else
|
|
828
|
+
else {
|
|
829
|
+
const check = checkWranglerConfig(this.projectRoot, databases);
|
|
830
|
+
if (!check.ok && !check.tomlOnly && this.config.command === "build") throw new Error(`[durable-db] wrangler config is missing Durable Object bindings/migrations for discovered database(s) — deploying this build would ship a worker without them. Add the JSON from the warning above to ${check.configPath ? path.basename(check.configPath) : "wrangler.jsonc"}, or opt in to automatic patching with durableDb({ patchWranglerConfig: true }).`);
|
|
831
|
+
}
|
|
813
832
|
}
|
|
814
833
|
this.initialized = true;
|
|
815
834
|
}
|
|
@@ -856,7 +875,11 @@ var PluginState = class {
|
|
|
856
875
|
triggerFullReload() {
|
|
857
876
|
if (!this.devServer) return;
|
|
858
877
|
const environments = this.devServer.environments;
|
|
859
|
-
if (environments) for (const env of Object.
|
|
878
|
+
if (environments) for (const [name, env] of Object.entries(environments)) try {
|
|
879
|
+
env.hot?.send({ type: "full-reload" });
|
|
880
|
+
} catch (error) {
|
|
881
|
+
debugVite("Skipped full-reload for environment %s (hot channel not ready): %O", name, error);
|
|
882
|
+
}
|
|
860
883
|
else this.devServer.ws.send({ type: "full-reload" });
|
|
861
884
|
}
|
|
862
885
|
};
|
|
@@ -899,6 +922,10 @@ function durableDb(options = {}) {
|
|
|
899
922
|
fs.mkdirSync(devPaths.cacheDir, { recursive: true });
|
|
900
923
|
let reloadTimer = null;
|
|
901
924
|
const onDevStateChange = () => {
|
|
925
|
+
if (state.isWithinSelfDevStateWriteWindow()) {
|
|
926
|
+
debugVite("Ignoring dev cache event caused by the plugin itself");
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
902
929
|
if (reloadTimer) clearTimeout(reloadTimer);
|
|
903
930
|
reloadTimer = setTimeout(() => {
|
|
904
931
|
debugVite("Dev state changed; reloading durable-db modules");
|
|
@@ -931,7 +958,10 @@ function durableDb(options = {}) {
|
|
|
931
958
|
let epoch = null;
|
|
932
959
|
if (isDev$1) {
|
|
933
960
|
const devState = loadDevState(state.projectRoot);
|
|
934
|
-
if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile))
|
|
961
|
+
if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile)) {
|
|
962
|
+
state.markSelfDevStateWrite();
|
|
963
|
+
saveDevState(state.projectRoot, devState);
|
|
964
|
+
}
|
|
935
965
|
epoch = devState.epoch;
|
|
936
966
|
}
|
|
937
967
|
return { code: generateDevEpochModule(epoch) };
|