durable-utils
Version:
Utilities for Cloudflare Durable Objects and Workers, including SQL migrations, sharding and retry utilities, and more.
110 lines (108 loc) • 4.34 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/sql-migrations.ts
var sql_migrations_exports = {};
__export(sql_migrations_exports, {
SQLSchemaMigrations: () => SQLSchemaMigrations
});
module.exports = __toCommonJS(sql_migrations_exports);
var SQLSchemaMigrations = class {
#_config;
#_migrations;
#_lastMigrationMonotonicId = -1;
constructor(config) {
this.#_config = config;
const migrations = [...config.migrations];
migrations.sort((a, b) => a.idMonotonicInc - b.idMonotonicInc);
const idSeen = /* @__PURE__ */ new Set();
migrations.forEach((m) => {
if (m.idMonotonicInc < 0) {
throw new Error(`migration ID cannot be negative: ${m.idMonotonicInc}`);
}
if (idSeen.has(m.idMonotonicInc)) {
throw new Error(`duplicate migration ID detected: ${m.idMonotonicInc}`);
}
idSeen.add(m.idMonotonicInc);
});
this.#_migrations = migrations;
}
/**
* This is a quick check based on the in memory tracker of last migration ran,
* therefore this always returns `true` until `runAll` runs once.
* @returns True if the `migrations` list provided has not been ran in full yet.
*/
hasMigrationsToRun() {
if (!this.#_migrations.length) {
return false;
}
return this.#_lastMigrationMonotonicId !== this.#_migrations[this.#_migrations.length - 1].idMonotonicInc;
}
/**
* Runs all the migrations that haven't already ran. The `idMonotonicInc` of each migration is used
* to track which migrations ran or not. New migrations should always have higher `idMonotonicInc`
* than older ones!
*
* @param sqlGen An optional callback function to generate the SQL statement of a given migration at runtime.
* If the migration entry already has a valid `sql` statement this callback is NOT called.
* @returns The numbers of rows read and written throughout the migration execution.
*/
async runAll(sqlGen) {
const result = {
rowsRead: 0,
rowsWritten: 0
};
if (!this.hasMigrationsToRun()) {
return result;
}
this.#_lastMigrationMonotonicId = await this.#_config.doStorage.get(this.#_lastMigrationIDKeyName()) ?? -1;
let idx = 0, sz = this.#_migrations.length;
while (idx < sz && this.#_migrations[idx].idMonotonicInc <= this.#_lastMigrationMonotonicId) {
idx += 1;
}
if (idx >= sz) {
return result;
}
const doSql = this.#_config.doStorage.sql;
const migrationsToRun = this.#_migrations.slice(idx);
await this.#_config.doStorage.transaction(async () => {
let _lastMigrationMonotonicId = this.#_lastMigrationMonotonicId;
migrationsToRun.forEach((migration) => {
let query = migration.sql ?? sqlGen?.(migration.idMonotonicInc);
if (!query) {
throw new Error(`migration with neither 'sql' nor 'sqlGen' provided: ${migration.idMonotonicInc}`);
}
const cursor = doSql.exec(query);
let _ = cursor.toArray();
result.rowsRead += cursor.rowsRead;
result.rowsWritten += cursor.rowsWritten;
_lastMigrationMonotonicId = migration.idMonotonicInc;
});
this.#_lastMigrationMonotonicId = _lastMigrationMonotonicId;
await this.#_config.doStorage.put(this.#_lastMigrationIDKeyName(), this.#_lastMigrationMonotonicId);
});
return result;
}
#_lastMigrationIDKeyName() {
return this.#_config.keyNameTrackingLastMigrationID ?? "__sql_migrations_lastID";
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
SQLSchemaMigrations
});