@dudousxd/nestjs-durable-store-prisma 0.28.0 → 0.29.1

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.cts CHANGED
@@ -125,6 +125,35 @@ interface DurablePrismaClient extends DurablePrismaTx {
125
125
  /** Prisma's interactive-transaction form: runs `fn` with a tx-scoped client and commits on resolve. */
126
126
  $transaction<T>(fn: (tx: DurablePrismaTx) => Promise<T>): Promise<T>;
127
127
  }
128
+ /**
129
+ * The `namespace` read boundary as a spreadable Prisma `where` fragment.
130
+ *
131
+ * `undefined` means NO RESTRICTION — `{}` — because that is the operator (control-plane) view that
132
+ * sees every tenant, and it is what the engine passes when it runs unscoped. It does NOT mean
133
+ * "namespace IS NULL": the column is NOT NULL, so `{ namespace: undefined }` would be Prisma's
134
+ * "ignore this predicate" anyway, but `{ namespace: null }` would match nothing in production while
135
+ * still looking correct in a single-tenant test where every worker polls unscoped.
136
+ *
137
+ * A named namespace is plain equality, so a worker sees only its own tenant's rows — the boundary
138
+ * {@link WorkflowRun.namespace} promises for the four worker paths (pick up, recover, resume timers,
139
+ * time out).
140
+ */
141
+ /** Options for a {@link PrismaStateStore}. */
142
+ interface PrismaStateStoreOptions {
143
+ /**
144
+ * The schema (Postgres) or database (MySQL) the durable tables live in. Put the same name on the
145
+ * durable models (`@@schema("durable")`, with `schemas = [...]` on your datasource) so the Prisma
146
+ * client qualifies its own queries; this option qualifies the store's raw SQL. Never set
147
+ * `search_path` (or the URL's `?schema=`) for this. Postgres only: Prisma has no `@@schema` on
148
+ * MySQL, and SQLite has no schemas, so either fails at construction. Default: unqualified.
149
+ */
150
+ schema?: string | undefined;
151
+ }
152
+ /**
153
+ * Validate a durable `schema` option: an identifier of at most 63 characters. Returns it, or
154
+ * `undefined` when none is set.
155
+ */
156
+ declare function durableSchemaName(schema: string | undefined): string | undefined;
128
157
  /**
129
158
  * Prisma-backed `StateStore`. Pass your `PrismaClient` after adding the models from
130
159
  * `prisma/schema.prisma` to your schema. JSON columns carry the run/step payloads directly;
@@ -143,7 +172,8 @@ declare class PrismaStateStore implements StateStore {
143
172
  readonly claimPendingRuns?: (limit: number, owner: string, leaseUntilMs: number, nowMs: number, namespace?: string) => Promise<WorkflowRun[]>;
144
173
  /** Raw single-statement writes on Postgres/MySQL (Prisma wraps `updateMany` in a transaction). */
145
174
  private readonly fast?;
146
- constructor(db: DurablePrismaClient);
175
+ private readonly schema;
176
+ constructor(db: DurablePrismaClient, options?: PrismaStateStoreOptions);
147
177
  tryAdmitSingleton(runId: string, tag: string, workflow: string, limit: number, retryWakeAt?: number): Promise<boolean>;
148
178
  createRun(run: WorkflowRun): Promise<void>;
149
179
  updateRun(runId: string, inputPatch: Partial<WorkflowRun>): Promise<void>;
@@ -279,4 +309,4 @@ declare class PrismaStateStore implements StateStore {
279
309
  */
280
310
  declare function durableManagedTables(): string[];
281
311
 
282
- export { type DurablePrismaClient, type DurablePrismaTx, PrismaStateStore, durableManagedTables };
312
+ export { type DurablePrismaClient, type DurablePrismaTx, PrismaStateStore, type PrismaStateStoreOptions, durableManagedTables, durableSchemaName };
package/dist/index.d.ts CHANGED
@@ -125,6 +125,35 @@ interface DurablePrismaClient extends DurablePrismaTx {
125
125
  /** Prisma's interactive-transaction form: runs `fn` with a tx-scoped client and commits on resolve. */
126
126
  $transaction<T>(fn: (tx: DurablePrismaTx) => Promise<T>): Promise<T>;
127
127
  }
128
+ /**
129
+ * The `namespace` read boundary as a spreadable Prisma `where` fragment.
130
+ *
131
+ * `undefined` means NO RESTRICTION — `{}` — because that is the operator (control-plane) view that
132
+ * sees every tenant, and it is what the engine passes when it runs unscoped. It does NOT mean
133
+ * "namespace IS NULL": the column is NOT NULL, so `{ namespace: undefined }` would be Prisma's
134
+ * "ignore this predicate" anyway, but `{ namespace: null }` would match nothing in production while
135
+ * still looking correct in a single-tenant test where every worker polls unscoped.
136
+ *
137
+ * A named namespace is plain equality, so a worker sees only its own tenant's rows — the boundary
138
+ * {@link WorkflowRun.namespace} promises for the four worker paths (pick up, recover, resume timers,
139
+ * time out).
140
+ */
141
+ /** Options for a {@link PrismaStateStore}. */
142
+ interface PrismaStateStoreOptions {
143
+ /**
144
+ * The schema (Postgres) or database (MySQL) the durable tables live in. Put the same name on the
145
+ * durable models (`@@schema("durable")`, with `schemas = [...]` on your datasource) so the Prisma
146
+ * client qualifies its own queries; this option qualifies the store's raw SQL. Never set
147
+ * `search_path` (or the URL's `?schema=`) for this. Postgres only: Prisma has no `@@schema` on
148
+ * MySQL, and SQLite has no schemas, so either fails at construction. Default: unqualified.
149
+ */
150
+ schema?: string | undefined;
151
+ }
152
+ /**
153
+ * Validate a durable `schema` option: an identifier of at most 63 characters. Returns it, or
154
+ * `undefined` when none is set.
155
+ */
156
+ declare function durableSchemaName(schema: string | undefined): string | undefined;
128
157
  /**
129
158
  * Prisma-backed `StateStore`. Pass your `PrismaClient` after adding the models from
130
159
  * `prisma/schema.prisma` to your schema. JSON columns carry the run/step payloads directly;
@@ -143,7 +172,8 @@ declare class PrismaStateStore implements StateStore {
143
172
  readonly claimPendingRuns?: (limit: number, owner: string, leaseUntilMs: number, nowMs: number, namespace?: string) => Promise<WorkflowRun[]>;
144
173
  /** Raw single-statement writes on Postgres/MySQL (Prisma wraps `updateMany` in a transaction). */
145
174
  private readonly fast?;
146
- constructor(db: DurablePrismaClient);
175
+ private readonly schema;
176
+ constructor(db: DurablePrismaClient, options?: PrismaStateStoreOptions);
147
177
  tryAdmitSingleton(runId: string, tag: string, workflow: string, limit: number, retryWakeAt?: number): Promise<boolean>;
148
178
  createRun(run: WorkflowRun): Promise<void>;
149
179
  updateRun(runId: string, inputPatch: Partial<WorkflowRun>): Promise<void>;
@@ -279,4 +309,4 @@ declare class PrismaStateStore implements StateStore {
279
309
  */
280
310
  declare function durableManagedTables(): string[];
281
311
 
282
- export { type DurablePrismaClient, type DurablePrismaTx, PrismaStateStore, durableManagedTables };
312
+ export { type DurablePrismaClient, type DurablePrismaTx, PrismaStateStore, type PrismaStateStoreOptions, durableManagedTables, durableSchemaName };
package/dist/index.js CHANGED
@@ -6,6 +6,21 @@ import { LIFECYCLE_REGISTRY_WORKFLOW, RUN_VALUE_FACET_SCAN, SINGLETON_ACTIVE_STA
6
6
  var RETENTION_EXCLUDED = [
7
7
  LIFECYCLE_REGISTRY_WORKFLOW
8
8
  ];
9
+ var SCHEMA_NAME = /^[A-Za-z_][A-Za-z0-9_$]*$/;
10
+ function durableSchemaName(schema) {
11
+ if (schema === void 0) return void 0;
12
+ if (!SCHEMA_NAME.test(schema) || schema.length > 63) {
13
+ throw new Error(`[nestjs-durable] invalid schema ${JSON.stringify(schema)}: use letters, digits, _ or $ (not first), at most 63 characters.`);
14
+ }
15
+ return schema;
16
+ }
17
+ __name(durableSchemaName, "durableSchemaName");
18
+ function rawTable(unqualified, schema, dialect) {
19
+ if (schema === void 0) return unqualified;
20
+ const name = unqualified.replace(/^["`]|["`]$/g, "");
21
+ return dialect === "postgres" ? `"${schema}"."${name}"` : `\`${schema}\`.\`${name}\``;
22
+ }
23
+ __name(rawTable, "rawTable");
9
24
  function namespaceWhere(namespace) {
10
25
  if (namespace === void 0) return {};
11
26
  return {
@@ -26,13 +41,21 @@ var PrismaStateStore = class {
26
41
  claimPendingRuns;
27
42
  /** Raw single-statement writes on Postgres/MySQL (Prisma wraps `updateMany` in a transaction). */
28
43
  fast;
29
- constructor(db) {
44
+ schema;
45
+ constructor(db, options = {}) {
30
46
  this.db = db;
31
47
  const provider = db._activeProvider;
48
+ this.schema = durableSchemaName(options.schema);
49
+ if (this.schema !== void 0 && provider === "sqlite") {
50
+ throw new Error(`[nestjs-durable] store-prisma: the schema option (${JSON.stringify(this.schema)}) is not supported on SQLite, which has no schemas. Remove it.`);
51
+ }
52
+ if (this.schema !== void 0 && provider === "mysql") {
53
+ throw new Error(`[nestjs-durable] store-prisma: the schema option (${JSON.stringify(this.schema)}) is not supported on MySQL, where Prisma has no multi-schema support (\`@@schema\`). Point the client's connection at that database instead, or use the MikroORM or TypeORM store.`);
54
+ }
32
55
  const raw = typeof db.$queryRawUnsafe === "function";
33
56
  const dialect = raw && provider === "postgresql" ? "postgres" : raw && provider === "mysql" ? "mysql" : void 0;
34
57
  if (!dialect) return;
35
- const fast = new PrismaRoundTrips(db, dialect, this);
58
+ const fast = new PrismaRoundTrips(db, dialect, this, this.schema);
36
59
  this.fast = fast;
37
60
  this.insertCheckpointIfAbsent = (cp) => fast.insertCheckpointIfAbsent(cp);
38
61
  this.settleResultsIfPending = (results) => fast.settleResultsIfPending(results);
@@ -48,7 +71,7 @@ var PrismaStateStore = class {
48
71
  in: SINGLETON_ACTIVE_STATUSES
49
72
  }
50
73
  };
51
- const lockRows = rowLockDialect(this.db);
74
+ const lockRows = rowLockDialect(this.db, this.schema);
52
75
  const claimants = lockRows ? singletonClaimantIds(
53
76
  // The primary, under the read-replicas extension: a lagging replica would leave rows out.
54
77
  await primaryOf(this.db).durableWorkflowRun.findMany({
@@ -450,7 +473,9 @@ var PrismaStateStore = class {
450
473
  error: jsonOrNull(s.error),
451
474
  events: jsonOrNull(s.events),
452
475
  startedAt: s.startedAt,
453
- finishedAt: s.finishedAt
476
+ finishedAt: s.finishedAt,
477
+ // A settled step has no dispatch lease left.
478
+ wakeAt: null
454
479
  }
455
480
  });
456
481
  wrote[i] = count > 0;
@@ -464,7 +489,7 @@ var PrismaStateStore = class {
464
489
  const raw = tx;
465
490
  for (let at = 0; at < firsts.length; at += 500) {
466
491
  const chunk = firsts.slice(at, at + 500);
467
- const won = await dialect(raw, chunk.map((i) => settlements[i]));
492
+ const won = await dialect(raw, chunk.map((i) => settlements[i]), this.schema);
468
493
  for (const i of chunk) {
469
494
  const s = settlements[i];
470
495
  wrote[i] = won.has(checkpointKey(s.runId, s.seq));
@@ -1718,14 +1743,14 @@ function primaryOf(db) {
1718
1743
  return typeof client.$primary === "function" ? client.$primary() : db;
1719
1744
  }
1720
1745
  __name(primaryOf, "primaryOf");
1721
- function rowLockDialect(db) {
1746
+ function rowLockDialect(db, schema) {
1722
1747
  const client = db;
1723
1748
  if (typeof client.$queryRawUnsafe !== "function") return void 0;
1724
1749
  if (client._activeProvider === "postgresql") {
1725
- return (tx, ids) => tx.$queryRawUnsafe(`SELECT id FROM "durable_workflow_runs" WHERE id IN (${ids.map((_, i) => `$${i + 1}`).join(", ")}) ORDER BY id FOR UPDATE`, ...ids);
1750
+ return (tx, ids) => tx.$queryRawUnsafe(`SELECT id FROM ${rawTable('"durable_workflow_runs"', schema, "postgres")} WHERE id IN (${ids.map((_, i) => `$${i + 1}`).join(", ")}) ORDER BY id FOR UPDATE`, ...ids);
1726
1751
  }
1727
1752
  if (client._activeProvider === "mysql") {
1728
- return (tx, ids) => tx.$queryRawUnsafe(`SELECT id FROM durable_workflow_runs WHERE id IN (${ids.map(() => "?").join(", ")}) ORDER BY id FOR UPDATE`, ...ids);
1753
+ return (tx, ids) => tx.$queryRawUnsafe(`SELECT id FROM ${rawTable("durable_workflow_runs", schema, "mysql")} WHERE id IN (${ids.map(() => "?").join(", ")}) ORDER BY id FOR UPDATE`, ...ids);
1729
1754
  }
1730
1755
  return void 0;
1731
1756
  }
@@ -1739,7 +1764,7 @@ function rawSettleDialect(db) {
1739
1764
  return void 0;
1740
1765
  }
1741
1766
  __name(rawSettleDialect, "rawSettleDialect");
1742
- var settleRowsPostgres = /* @__PURE__ */ __name(async (db, settlements) => {
1767
+ var settleRowsPostgres = /* @__PURE__ */ __name(async (db, settlements, schema) => {
1743
1768
  const values = [];
1744
1769
  const rows = settlements.map((s) => {
1745
1770
  const n = values.length;
@@ -1747,18 +1772,19 @@ var settleRowsPostgres = /* @__PURE__ */ __name(async (db, settlements) => {
1747
1772
  const p = /* @__PURE__ */ __name((k) => `$${n + k}`, "p");
1748
1773
  return `(${p(1)}::text, ${p(2)}::integer, ${p(3)}::text, ${p(4)}::jsonb, ${p(5)}::jsonb, ${p(6)}::jsonb, (${p(7)}::timestamptz AT TIME ZONE 'UTC'), (${p(8)}::timestamptz AT TIME ZONE 'UTC'))`;
1749
1774
  });
1750
- const written = await db.$queryRawUnsafe(`UPDATE "durable_step_checkpoints" AS c SET status = v.status, output = v.output,
1751
- error = v.error, events = v.events, started_at = v.started_at, finished_at = v.finished_at
1775
+ const written = await db.$queryRawUnsafe(`UPDATE ${rawTable('"durable_step_checkpoints"', schema, "postgres")} AS c SET status = v.status, output = v.output,
1776
+ error = v.error, events = v.events, started_at = v.started_at, finished_at = v.finished_at,
1777
+ wake_at = NULL
1752
1778
  FROM (VALUES ${rows.join(", ")}) AS v(run_id, seq, status, output, error, events, started_at,
1753
1779
  finished_at)
1754
1780
  WHERE c.run_id = v.run_id AND c.seq = v.seq AND c.status = 'pending'
1755
1781
  RETURNING c.run_id, c.seq`, ...values);
1756
1782
  return new Set(written.map((row) => checkpointKey(row.run_id, Number(row.seq))));
1757
1783
  }, "settleRowsPostgres");
1758
- var settleRowsMysql = /* @__PURE__ */ __name(async (db, settlements) => {
1784
+ var settleRowsMysql = /* @__PURE__ */ __name(async (db, settlements, schema) => {
1759
1785
  const pending = /* @__PURE__ */ new Set();
1760
1786
  for (const [runId, seqs] of seqsByRun(settlements)) {
1761
- const rows2 = await db.$queryRawUnsafe(`SELECT run_id, seq FROM durable_step_checkpoints WHERE run_id = ? AND seq IN (${seqs.map(() => "?").join(", ")}) AND status = 'pending' FOR UPDATE`, runId, ...seqs);
1787
+ const rows2 = await db.$queryRawUnsafe(`SELECT run_id, seq FROM ${rawTable("durable_step_checkpoints", schema, "mysql")} WHERE run_id = ? AND seq IN (${seqs.map(() => "?").join(", ")}) AND status = 'pending' FOR UPDATE`, runId, ...seqs);
1762
1788
  for (const row of rows2) pending.add(checkpointKey(row.run_id, Number(row.seq)));
1763
1789
  }
1764
1790
  const won = settlements.filter((s) => pending.has(checkpointKey(s.runId, s.seq)));
@@ -1769,10 +1795,11 @@ var settleRowsMysql = /* @__PURE__ */ __name(async (db, settlements) => {
1769
1795
  values.push(s.runId, s.seq, s.status, jsonText(s.output), jsonText(s.error), jsonText(s.events), at(s.startedAt), at(s.finishedAt));
1770
1796
  return i === 0 ? "SELECT ? AS run_id, ? AS seq, ? AS status, ? AS output, ? AS error, ? AS events, ? AS started_at, ? AS finished_at" : "SELECT ?, ?, ?, ?, ?, ?, ?, ?";
1771
1797
  });
1772
- const updated = await db.$executeRawUnsafe(`UPDATE durable_step_checkpoints AS c JOIN (${rows.join(" UNION ALL ")}) AS v
1798
+ const updated = await db.$executeRawUnsafe(`UPDATE ${rawTable("durable_step_checkpoints", schema, "mysql")} AS c JOIN (${rows.join(" UNION ALL ")}) AS v
1773
1799
  ON c.run_id = v.run_id AND c.seq = v.seq
1774
1800
  SET c.status = v.status, c.output = CAST(v.output AS JSON), c.error = CAST(v.error AS JSON),
1775
- c.events = CAST(v.events AS JSON), c.started_at = v.started_at, c.finished_at = v.finished_at
1801
+ c.events = CAST(v.events AS JSON), c.started_at = v.started_at, c.finished_at = v.finished_at,
1802
+ c.wake_at = NULL
1776
1803
  WHERE c.status = 'pending'`, ...values);
1777
1804
  if (updated !== won.length) {
1778
1805
  throw new Error("a checkpoint of the batch was settled while the batch was written");
@@ -1787,7 +1814,7 @@ var settleRowsSqlite = /* @__PURE__ */ __name(async (db, settlements) => {
1787
1814
  });
1788
1815
  const written = await db.$queryRawUnsafe(`WITH v(run_id, seq, status, output, error, events, started_at, finished_at) AS (VALUES ${rows.join(", ")})
1789
1816
  UPDATE durable_step_checkpoints SET status = v.status, output = v.output, error = v.error,
1790
- events = v.events, started_at = v.started_at, finished_at = v.finished_at
1817
+ events = v.events, started_at = v.started_at, finished_at = v.finished_at, wake_at = NULL
1791
1818
  FROM v
1792
1819
  WHERE durable_step_checkpoints.run_id = v.run_id AND durable_step_checkpoints.seq = v.seq
1793
1820
  AND durable_step_checkpoints.status = 'pending'
@@ -1894,17 +1921,23 @@ var PrismaRoundTrips = class PrismaRoundTrips2 {
1894
1921
  }
1895
1922
  db;
1896
1923
  store;
1924
+ schema;
1897
1925
  pg;
1898
- constructor(db, dialect, store) {
1926
+ constructor(db, dialect, store, schema) {
1899
1927
  this.db = db;
1900
1928
  this.store = store;
1929
+ this.schema = schema;
1901
1930
  this.pg = dialect === "postgres";
1902
1931
  }
1932
+ /** A durable table as this statement wrote it unqualified, with the schema when one is set. */
1933
+ t(unqualified) {
1934
+ return rawTable(unqualified, this.schema, this.pg ? "postgres" : "mysql");
1935
+ }
1903
1936
  get raw() {
1904
1937
  return this.db;
1905
1938
  }
1906
1939
  async tryLockRunAndGet(runId, owner, leaseUntilMs, nowMs) {
1907
- const rows = await this.raw.$queryRawUnsafe(`UPDATE "durable_workflow_runs" SET locked_by = $1, locked_until = ($2::timestamptz AT TIME ZONE 'UTC') WHERE id = $3 AND (locked_until IS NULL OR locked_until <= ($4::timestamptz AT TIME ZONE 'UTC')) RETURNING *`, owner, new Date(leaseUntilMs).toISOString(), runId, new Date(nowMs).toISOString());
1940
+ const rows = await this.raw.$queryRawUnsafe(`UPDATE ${this.t('"durable_workflow_runs"')} SET locked_by = $1, locked_until = ($2::timestamptz AT TIME ZONE 'UTC') WHERE id = $3 AND (locked_until IS NULL OR locked_until <= ($4::timestamptz AT TIME ZONE 'UTC')) RETURNING *`, owner, new Date(leaseUntilMs).toISOString(), runId, new Date(nowMs).toISOString());
1908
1941
  const [row] = rows;
1909
1942
  return row ? fromRunRow(fromRawRow(row)) : null;
1910
1943
  }
@@ -2024,7 +2057,7 @@ var PrismaRoundTrips = class PrismaRoundTrips2 {
2024
2057
  const names = columns.map(([name]) => this.q(name)).join(", ");
2025
2058
  const marks = columns.map(([, kind], i) => this.param(kind, i + 1)).join(", ");
2026
2059
  const values = columns.map(([, kind, v]) => this.value(kind, v));
2027
- const insert = `INSERT INTO ${this.q("durable_step_checkpoints")} (${names}) VALUES (${marks})`;
2060
+ const insert = `INSERT INTO ${this.t(this.q("durable_step_checkpoints"))} (${names}) VALUES (${marks})`;
2028
2061
  if (this.pg) {
2029
2062
  const rows = await this.raw.$queryRawUnsafe(`${insert} ON CONFLICT (run_id, seq) DO NOTHING RETURNING seq`, ...values);
2030
2063
  return rows.length === 1;
@@ -2132,12 +2165,12 @@ var PrismaRoundTrips = class PrismaRoundTrips2 {
2132
2165
  values.push(status);
2133
2166
  return this.param("text", values.length);
2134
2167
  });
2135
- return this.raw.$executeRawUnsafe(`UPDATE ${this.q("durable_workflow_runs")} SET ${set.join(", ")} WHERE id = ${id} AND status IN (${statuses.join(", ")})`, ...values);
2168
+ return this.raw.$executeRawUnsafe(`UPDATE ${this.t(this.q("durable_workflow_runs"))} SET ${set.join(", ")} WHERE id = ${id} AND status IN (${statuses.join(", ")})`, ...values);
2136
2169
  }
2137
2170
  /** `releaseRunLock` as one raw UPDATE (no transaction around it). */
2138
2171
  async releaseRunLock(runId, owner) {
2139
2172
  const where = owner === void 0 ? "" : ` AND locked_by = ${this.param("text", 2)}`;
2140
- await this.raw.$executeRawUnsafe(`UPDATE ${this.q("durable_workflow_runs")} SET locked_by = NULL, locked_until = NULL WHERE id = ${this.param("text", 1)}${where}`, runId, ...owner === void 0 ? [] : [
2173
+ await this.raw.$executeRawUnsafe(`UPDATE ${this.t(this.q("durable_workflow_runs"))} SET locked_by = NULL, locked_until = NULL WHERE id = ${this.param("text", 1)}${where}`, runId, ...owner === void 0 ? [] : [
2141
2174
  owner
2142
2175
  ]);
2143
2176
  }
@@ -2153,18 +2186,18 @@ var PrismaRoundTrips = class PrismaRoundTrips2 {
2153
2186
  ];
2154
2187
  });
2155
2188
  if (sent.length === 0) return out;
2156
- const finished = `NOT EXISTS (SELECT 1 FROM durable_workflow_runs r WHERE r.id = c.run_id AND r.status IN ('cancelled', 'completed'))`;
2189
+ const finished = `NOT EXISTS (SELECT 1 FROM ${this.t("durable_workflow_runs")} r WHERE r.id = c.run_id AND r.status IN ('cancelled', 'completed'))`;
2157
2190
  if (!this.pg) {
2158
2191
  if (sent.length > 1) return settleResultsWithPlainCalls(this.store, results);
2159
2192
  const i = sent[0];
2160
2193
  const s = results[i];
2161
2194
  const done = s.status === "completed";
2162
2195
  const at = /* @__PURE__ */ __name((d) => d.toISOString().replace("T", " ").replace("Z", ""), "at");
2163
- const wrote = await this.raw.$executeRawUnsafe(`UPDATE durable_step_checkpoints c SET c.status = ?, c.output = ${done ? "CAST(? AS JSON)" : "c.output"}, c.error = CAST(? AS JSON), c.events = COALESCE(CAST(? AS JSON), c.events), c.started_at = COALESCE(?, c.started_at), c.finished_at = ? WHERE c.run_id = ? AND c.seq = ? AND c.status = 'pending' AND ${finished}`, s.status, ...done ? [
2196
+ const wrote = await this.raw.$executeRawUnsafe(`UPDATE ${this.t("durable_step_checkpoints")} c SET c.status = ?, c.output = ${done ? "CAST(? AS JSON)" : "c.output"}, c.error = CAST(? AS JSON), c.events = COALESCE(CAST(? AS JSON), c.events), c.started_at = COALESCE(?, c.started_at), c.finished_at = ?, c.wake_at = NULL WHERE c.run_id = ? AND c.seq = ? AND c.status = 'pending' AND ${finished}`, s.status, ...done ? [
2164
2197
  jsonText(s.output)
2165
2198
  ] : [], jsonText(s.error), jsonText(s.events), s.startedAt ? at(s.startedAt) : null, at(s.finishedAt), s.runId, s.seq);
2166
2199
  if (wrote !== 1) return out;
2167
- const [row] = await this.raw.$queryRawUnsafe(`SELECT ${SETTLED_CHECKPOINT_COLUMNS} FROM durable_step_checkpoints WHERE run_id = ? AND seq = ?`, s.runId, s.seq);
2200
+ const [row] = await this.raw.$queryRawUnsafe(`SELECT ${SETTLED_CHECKPOINT_COLUMNS} FROM ${this.t("durable_step_checkpoints")} WHERE run_id = ? AND seq = ?`, s.runId, s.seq);
2168
2201
  out[i] = row ? fromCheckpointRow(fromRawRow({
2169
2202
  ...row,
2170
2203
  input: null
@@ -2181,7 +2214,7 @@ var PrismaRoundTrips = class PrismaRoundTrips2 {
2181
2214
  const p = /* @__PURE__ */ __name((k) => `$${n + k}`, "p");
2182
2215
  return `(${p(1)}::text, ${p(2)}::integer, ${p(3)}::text, ${p(4)}::jsonb, ${p(5)}::jsonb, ${p(6)}::jsonb, (${p(7)}::timestamptz AT TIME ZONE 'UTC'), (${p(8)}::timestamptz AT TIME ZONE 'UTC'))`;
2183
2216
  });
2184
- const settled = await this.raw.$queryRawUnsafe(`UPDATE "durable_step_checkpoints" AS c SET status = v.status, output = CASE WHEN v.status = 'completed' THEN v.output ELSE c.output END, error = v.error, events = COALESCE(v.events, c.events), started_at = COALESCE(v.started_at, c.started_at), finished_at = v.finished_at FROM (VALUES ${rows.join(", ")}) AS v(run_id, seq, status, output, error, events, started_at, finished_at) WHERE c.run_id = v.run_id AND c.seq = v.seq AND c.status = 'pending' AND ${finished} RETURNING ${SETTLED_CHECKPOINT_COLUMNS.split(", ").map((col) => `c.${col}`).join(", ")}`, ...values);
2217
+ const settled = await this.raw.$queryRawUnsafe(`UPDATE ${this.t('"durable_step_checkpoints"')} AS c SET status = v.status, output = CASE WHEN v.status = 'completed' THEN v.output ELSE c.output END, error = v.error, events = COALESCE(v.events, c.events), started_at = COALESCE(v.started_at, c.started_at), finished_at = v.finished_at, wake_at = NULL FROM (VALUES ${rows.join(", ")}) AS v(run_id, seq, status, output, error, events, started_at, finished_at) WHERE c.run_id = v.run_id AND c.seq = v.seq AND c.status = 'pending' AND ${finished} RETURNING ${SETTLED_CHECKPOINT_COLUMNS.split(", ").map((col) => `c.${col}`).join(", ")}`, ...values);
2185
2218
  const byKey = new Map(chunk.map((i) => {
2186
2219
  const s = results[i];
2187
2220
  return [
@@ -2205,7 +2238,7 @@ var PrismaRoundTrips = class PrismaRoundTrips2 {
2205
2238
  const sort = /* @__PURE__ */ __name((runs) => runs.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id)), "sort");
2206
2239
  if (this.pg) {
2207
2240
  const ns = namespace !== void 0 ? " AND namespace = $5" : "";
2208
- const rows = await this.raw.$queryRawUnsafe(`WITH claimed AS MATERIALIZED (SELECT id AS claimed_id FROM "durable_workflow_runs" WHERE status = 'pending' AND (locked_until IS NULL OR locked_until <= ($3::timestamptz AT TIME ZONE 'UTC'))${ns} ORDER BY created_at, id LIMIT $4 FOR UPDATE SKIP LOCKED) UPDATE "durable_workflow_runs" AS r SET locked_by = $1, locked_until = ($2::timestamptz AT TIME ZONE 'UTC') FROM claimed WHERE r.id = claimed.claimed_id RETURNING r.*`, owner, new Date(leaseUntilMs).toISOString(), new Date(nowMs).toISOString(), limit, ...namespace !== void 0 ? [
2241
+ const rows = await this.raw.$queryRawUnsafe(`WITH claimed AS MATERIALIZED (SELECT id AS claimed_id FROM ${this.t('"durable_workflow_runs"')} WHERE status = 'pending' AND (locked_until IS NULL OR locked_until <= ($3::timestamptz AT TIME ZONE 'UTC'))${ns} ORDER BY created_at, id LIMIT $4 FOR UPDATE SKIP LOCKED) UPDATE ${this.t('"durable_workflow_runs"')} AS r SET locked_by = $1, locked_until = ($2::timestamptz AT TIME ZONE 'UTC') FROM claimed WHERE r.id = claimed.claimed_id RETURNING r.*`, owner, new Date(leaseUntilMs).toISOString(), new Date(nowMs).toISOString(), limit, ...namespace !== void 0 ? [
2209
2242
  namespace
2210
2243
  ] : []);
2211
2244
  return sort(rows.map((raw) => fromRunRow(fromRawRow(raw))));
@@ -2214,11 +2247,11 @@ var PrismaRoundTrips = class PrismaRoundTrips2 {
2214
2247
  const raw = tx;
2215
2248
  const at = /* @__PURE__ */ __name((ms) => new Date(ms).toISOString().replace("T", " ").replace("Z", ""), "at");
2216
2249
  const ns = namespace !== void 0 ? " AND namespace = ?" : "";
2217
- const picked = (await raw.$queryRawUnsafe(`SELECT * FROM durable_workflow_runs WHERE status = 'pending' AND (locked_until IS NULL OR locked_until <= ?)${ns} ORDER BY created_at, id LIMIT ? FOR UPDATE SKIP LOCKED`, at(nowMs), ...namespace !== void 0 ? [
2250
+ const picked = (await raw.$queryRawUnsafe(`SELECT * FROM ${this.t("durable_workflow_runs")} WHERE status = 'pending' AND (locked_until IS NULL OR locked_until <= ?)${ns} ORDER BY created_at, id LIMIT ? FOR UPDATE SKIP LOCKED`, at(nowMs), ...namespace !== void 0 ? [
2218
2251
  namespace
2219
2252
  ] : [], limit)).map((row) => fromRunRow(fromRawRow(row)));
2220
2253
  if (picked.length === 0) return [];
2221
- await raw.$executeRawUnsafe(`UPDATE durable_workflow_runs SET locked_by = ?, locked_until = ? WHERE id IN (${picked.map(() => "?").join(", ")})`, owner, at(leaseUntilMs), ...picked.map((run) => run.id));
2254
+ await raw.$executeRawUnsafe(`UPDATE ${this.t("durable_workflow_runs")} SET locked_by = ?, locked_until = ? WHERE id IN (${picked.map(() => "?").join(", ")})`, owner, at(leaseUntilMs), ...picked.map((run) => run.id));
2222
2255
  return sort(picked.map((run) => ({
2223
2256
  ...run,
2224
2257
  lockedBy: owner,
@@ -2244,6 +2277,7 @@ function durableManagedTables() {
2244
2277
  __name(durableManagedTables, "durableManagedTables");
2245
2278
  export {
2246
2279
  PrismaStateStore,
2247
- durableManagedTables
2280
+ durableManagedTables,
2281
+ durableSchemaName
2248
2282
  };
2249
2283
  //# sourceMappingURL=index.js.map