@dudousxd/nestjs-durable-store-mikro-orm 0.36.0 → 0.38.0

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
@@ -160,8 +160,25 @@ declare class ScheduleEntity {
160
160
  createdAt: Date;
161
161
  updatedAt: Date;
162
162
  }
163
+ /**
164
+ * Validate a durable `schema` option: an identifier of at most 63 characters. Returns it, or
165
+ * `undefined` when none is set.
166
+ */
167
+ declare function durableSchemaName(schema: string | undefined): string | undefined;
168
+ /**
169
+ * Build the durable MikroORM entity schemas with column names pinned per `naming` (default
170
+ * `'snake_case'`). Register the result in your MikroORM config / `MikroOrmModule.forFeature`.
171
+ *
172
+ * ```ts
173
+ * entities: durableEntities({ naming: 'snake_case' })
174
+ * ```
175
+ *
176
+ * `schema` puts every durable table in that database schema (Postgres) or database (MySQL):
177
+ * `durableEntities({ schema: 'durable' })`. Not supported on SQLite.
178
+ */
163
179
  declare function durableEntities(options?: {
164
180
  naming?: DurableColumnNaming;
181
+ schema?: string;
165
182
  }): EntitySchema[];
166
183
  /** Durable entity schemas with the canonical `'snake_case'` column names. */
167
184
  declare const ENTITIES: EntitySchema<any, never, _mikro_orm_core.EntityCtor<any>>[];
@@ -192,6 +209,12 @@ interface DurableSchemaLogger {
192
209
  interface EnsureMikroOrmDurableSchemaOptions {
193
210
  /** Sink for the schema-repair warning. Defaults to `console`. */
194
211
  logger?: DurableSchemaLogger | undefined;
212
+ /**
213
+ * The schema (Postgres) or database (MySQL) of the durable tables. Defaults to the one the
214
+ * registered `durableEntities({ schema })` carry; when set, it must match them. Created when
215
+ * missing.
216
+ */
217
+ schema?: string | undefined;
195
218
  /**
196
219
  * MySQL only: the largest estimated row count (`information_schema.tables.table_rows`) of an
197
220
  * existing durable table on which the boot-time heal will run a column TYPE change. MySQL runs a
@@ -223,6 +246,12 @@ declare function mikroOrmDeferredAlterWarning(deferred: ReadonlyArray<{
223
246
  * noise, and a silent repair hides a migration-managed schema that has drifted from the library.
224
247
  */
225
248
  declare function mikroOrmSchemaRepairWarning(repairs: readonly string[]): string;
249
+ /**
250
+ * The schema (Postgres) or database (MySQL) the durable tables live in, read from the registered
251
+ * entities, or `undefined` when they are unqualified. A `configured` schema (the store's `schema`
252
+ * option) must match the entities, and SQLite takes none.
253
+ */
254
+ declare function durableTableSchema(orm: MikroORM, configured?: string | undefined): string | undefined;
226
255
  /**
227
256
  * Idempotently create/extend ONLY the durable tables (additive — never drops). Safe to run on every
228
257
  * boot (auto-schema) and from a MikroORM migration when you disable auto-schema:
@@ -281,6 +310,13 @@ interface MikroOrmStateStoreOptions {
281
310
  * `blockingAlterRowLimit` on `ensureMikroOrmDurableSchema`.
282
311
  */
283
312
  schemaBlockingAlterRowLimit?: number | undefined;
313
+ /**
314
+ * The schema (Postgres) or database (MySQL) the durable tables live in. Register the entities with
315
+ * the same one (`durableEntities({ schema })`); a mismatch fails at `ensureSchema()`. Every
316
+ * statement names it, so it works behind PgBouncer in transaction mode; never set `search_path`
317
+ * for this. Default: whatever the registered entities carry (unqualified unless built with one).
318
+ */
319
+ schema?: string | undefined;
284
320
  }
285
321
  /**
286
322
  * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);
@@ -479,4 +515,4 @@ declare class MikroOrmStateStore implements StateStore {
479
515
  removeBufferedEvent(id: string): Promise<boolean>;
480
516
  }
481
517
 
482
- export { BufferedEventEntity, BufferedEventRepository, BufferedSignalEntity, BufferedSignalRepository, DATETIME_PRECISION, DEFAULT_BLOCKING_ALTER_ROW_LIMIT, type DurableColumnNaming, type DurableSchemaLogger, ENTITIES, type EnsureMikroOrmDurableSchemaOptions, MikroOrmStateStore, type MikroOrmStateStoreOptions, RunAttributeEntity, RunAttributeRepository, ScheduleEntity, ScheduleRepository, SignalIdEntity, SignalIdRepository, SignalWaiterEntity, SignalWaiterRepository, StepCheckpointEntity, StepCheckpointRepository, WorkflowRunEntity, WorkflowRunRepository, durableEntities, durableManagedTables, ensureMikroOrmDurableSchema, mikroOrmDeferredAlterWarning, mikroOrmSchemaRepairWarning };
518
+ export { BufferedEventEntity, BufferedEventRepository, BufferedSignalEntity, BufferedSignalRepository, DATETIME_PRECISION, DEFAULT_BLOCKING_ALTER_ROW_LIMIT, type DurableColumnNaming, type DurableSchemaLogger, ENTITIES, type EnsureMikroOrmDurableSchemaOptions, MikroOrmStateStore, type MikroOrmStateStoreOptions, RunAttributeEntity, RunAttributeRepository, ScheduleEntity, ScheduleRepository, SignalIdEntity, SignalIdRepository, SignalWaiterEntity, SignalWaiterRepository, StepCheckpointEntity, StepCheckpointRepository, WorkflowRunEntity, WorkflowRunRepository, durableEntities, durableManagedTables, durableSchemaName, durableTableSchema, ensureMikroOrmDurableSchema, mikroOrmDeferredAlterWarning, mikroOrmSchemaRepairWarning };
package/dist/index.d.ts CHANGED
@@ -160,8 +160,25 @@ declare class ScheduleEntity {
160
160
  createdAt: Date;
161
161
  updatedAt: Date;
162
162
  }
163
+ /**
164
+ * Validate a durable `schema` option: an identifier of at most 63 characters. Returns it, or
165
+ * `undefined` when none is set.
166
+ */
167
+ declare function durableSchemaName(schema: string | undefined): string | undefined;
168
+ /**
169
+ * Build the durable MikroORM entity schemas with column names pinned per `naming` (default
170
+ * `'snake_case'`). Register the result in your MikroORM config / `MikroOrmModule.forFeature`.
171
+ *
172
+ * ```ts
173
+ * entities: durableEntities({ naming: 'snake_case' })
174
+ * ```
175
+ *
176
+ * `schema` puts every durable table in that database schema (Postgres) or database (MySQL):
177
+ * `durableEntities({ schema: 'durable' })`. Not supported on SQLite.
178
+ */
163
179
  declare function durableEntities(options?: {
164
180
  naming?: DurableColumnNaming;
181
+ schema?: string;
165
182
  }): EntitySchema[];
166
183
  /** Durable entity schemas with the canonical `'snake_case'` column names. */
167
184
  declare const ENTITIES: EntitySchema<any, never, _mikro_orm_core.EntityCtor<any>>[];
@@ -192,6 +209,12 @@ interface DurableSchemaLogger {
192
209
  interface EnsureMikroOrmDurableSchemaOptions {
193
210
  /** Sink for the schema-repair warning. Defaults to `console`. */
194
211
  logger?: DurableSchemaLogger | undefined;
212
+ /**
213
+ * The schema (Postgres) or database (MySQL) of the durable tables. Defaults to the one the
214
+ * registered `durableEntities({ schema })` carry; when set, it must match them. Created when
215
+ * missing.
216
+ */
217
+ schema?: string | undefined;
195
218
  /**
196
219
  * MySQL only: the largest estimated row count (`information_schema.tables.table_rows`) of an
197
220
  * existing durable table on which the boot-time heal will run a column TYPE change. MySQL runs a
@@ -223,6 +246,12 @@ declare function mikroOrmDeferredAlterWarning(deferred: ReadonlyArray<{
223
246
  * noise, and a silent repair hides a migration-managed schema that has drifted from the library.
224
247
  */
225
248
  declare function mikroOrmSchemaRepairWarning(repairs: readonly string[]): string;
249
+ /**
250
+ * The schema (Postgres) or database (MySQL) the durable tables live in, read from the registered
251
+ * entities, or `undefined` when they are unqualified. A `configured` schema (the store's `schema`
252
+ * option) must match the entities, and SQLite takes none.
253
+ */
254
+ declare function durableTableSchema(orm: MikroORM, configured?: string | undefined): string | undefined;
226
255
  /**
227
256
  * Idempotently create/extend ONLY the durable tables (additive — never drops). Safe to run on every
228
257
  * boot (auto-schema) and from a MikroORM migration when you disable auto-schema:
@@ -281,6 +310,13 @@ interface MikroOrmStateStoreOptions {
281
310
  * `blockingAlterRowLimit` on `ensureMikroOrmDurableSchema`.
282
311
  */
283
312
  schemaBlockingAlterRowLimit?: number | undefined;
313
+ /**
314
+ * The schema (Postgres) or database (MySQL) the durable tables live in. Register the entities with
315
+ * the same one (`durableEntities({ schema })`); a mismatch fails at `ensureSchema()`. Every
316
+ * statement names it, so it works behind PgBouncer in transaction mode; never set `search_path`
317
+ * for this. Default: whatever the registered entities carry (unqualified unless built with one).
318
+ */
319
+ schema?: string | undefined;
284
320
  }
285
321
  /**
286
322
  * MikroORM-backed `StateStore`. Works on any MikroORM driver — Postgres, MySQL, SQLite (tested);
@@ -479,4 +515,4 @@ declare class MikroOrmStateStore implements StateStore {
479
515
  removeBufferedEvent(id: string): Promise<boolean>;
480
516
  }
481
517
 
482
- export { BufferedEventEntity, BufferedEventRepository, BufferedSignalEntity, BufferedSignalRepository, DATETIME_PRECISION, DEFAULT_BLOCKING_ALTER_ROW_LIMIT, type DurableColumnNaming, type DurableSchemaLogger, ENTITIES, type EnsureMikroOrmDurableSchemaOptions, MikroOrmStateStore, type MikroOrmStateStoreOptions, RunAttributeEntity, RunAttributeRepository, ScheduleEntity, ScheduleRepository, SignalIdEntity, SignalIdRepository, SignalWaiterEntity, SignalWaiterRepository, StepCheckpointEntity, StepCheckpointRepository, WorkflowRunEntity, WorkflowRunRepository, durableEntities, durableManagedTables, ensureMikroOrmDurableSchema, mikroOrmDeferredAlterWarning, mikroOrmSchemaRepairWarning };
518
+ export { BufferedEventEntity, BufferedEventRepository, BufferedSignalEntity, BufferedSignalRepository, DATETIME_PRECISION, DEFAULT_BLOCKING_ALTER_ROW_LIMIT, type DurableColumnNaming, type DurableSchemaLogger, ENTITIES, type EnsureMikroOrmDurableSchemaOptions, MikroOrmStateStore, type MikroOrmStateStoreOptions, RunAttributeEntity, RunAttributeRepository, ScheduleEntity, ScheduleRepository, SignalIdEntity, SignalIdRepository, SignalWaiterEntity, SignalWaiterRepository, StepCheckpointEntity, StepCheckpointRepository, WorkflowRunEntity, WorkflowRunRepository, durableEntities, durableManagedTables, durableSchemaName, durableTableSchema, ensureMikroOrmDurableSchema, mikroOrmDeferredAlterWarning, mikroOrmSchemaRepairWarning };
package/dist/index.js CHANGED
@@ -178,6 +178,15 @@ var ScheduleEntity = class {
178
178
  createdAt;
179
179
  updatedAt;
180
180
  };
181
+ var SCHEMA_NAME = /^[A-Za-z_][A-Za-z0-9_$]*$/;
182
+ function durableSchemaName(schema) {
183
+ if (schema === void 0) return void 0;
184
+ if (!SCHEMA_NAME.test(schema) || schema.length > 63) {
185
+ throw new Error(`[nestjs-durable] invalid schema ${JSON.stringify(schema)}: use letters, digits, _ or $ (not first), at most 63 characters.`);
186
+ }
187
+ return schema;
188
+ }
189
+ __name(durableSchemaName, "durableSchemaName");
181
190
  function namespaceFilterCond(args) {
182
191
  if (args?.namespace === void 0) return {};
183
192
  return {
@@ -187,9 +196,14 @@ function namespaceFilterCond(args) {
187
196
  __name(namespaceFilterCond, "namespaceFilterCond");
188
197
  function durableEntities(options = {}) {
189
198
  const col = columnNamer(options.naming ?? "snake_case");
199
+ const schema = durableSchemaName(options.schema);
200
+ const where = schema === void 0 ? {} : {
201
+ schema
202
+ };
190
203
  const workflowRuns = new EntitySchema({
191
204
  class: WorkflowRunEntity,
192
205
  tableName: "durable_workflow_runs",
206
+ ...where,
193
207
  // Wired per schema rather than once on the class: `durableEntities` can be called again with a
194
208
  // different `naming`, and each call builds a distinct EntitySchema over the same class.
195
209
  repository: /* @__PURE__ */ __name(() => WorkflowRunRepository, "repository"),
@@ -381,6 +395,7 @@ function durableEntities(options = {}) {
381
395
  const stepCheckpoints = new EntitySchema({
382
396
  class: StepCheckpointEntity,
383
397
  tableName: "durable_step_checkpoints",
398
+ ...where,
384
399
  repository: /* @__PURE__ */ __name(() => StepCheckpointRepository, "repository"),
385
400
  // `(runId, parallelGroup, seq)` serves the run detail's per-group reads — `checkpointStats` with a
386
401
  // group and `queryCheckpoints` paging one fan in `seq` order — without scanning the whole run.
@@ -487,6 +502,7 @@ function durableEntities(options = {}) {
487
502
  const runAttributes = new EntitySchema({
488
503
  class: RunAttributeEntity,
489
504
  tableName: "durable_run_attributes",
505
+ ...where,
490
506
  repository: /* @__PURE__ */ __name(() => RunAttributeRepository, "repository"),
491
507
  // The search-attribute EXISTS join (see the class docstring) pushes equality/range predicates down
492
508
  // onto `(key, numValue)` / `(key, strValue)`; mirror the Prisma adapter so those scans stay indexed.
@@ -533,6 +549,7 @@ function durableEntities(options = {}) {
533
549
  const signalWaiters = new EntitySchema({
534
550
  class: SignalWaiterEntity,
535
551
  tableName: "durable_signal_waiters",
552
+ ...where,
536
553
  repository: /* @__PURE__ */ __name(() => SignalWaiterRepository, "repository"),
537
554
  // A run's waiters: the `ctx.all` join barrier probes them once per settled child.
538
555
  indexes: [
@@ -570,6 +587,7 @@ function durableEntities(options = {}) {
570
587
  const bufferedSignals = new EntitySchema({
571
588
  class: BufferedSignalEntity,
572
589
  tableName: "durable_buffered_signals",
590
+ ...where,
573
591
  repository: /* @__PURE__ */ __name(() => BufferedSignalRepository, "repository"),
574
592
  properties: {
575
593
  id: {
@@ -593,6 +611,7 @@ function durableEntities(options = {}) {
593
611
  const bufferedEvents = new EntitySchema({
594
612
  class: BufferedEventEntity,
595
613
  tableName: "durable_buffered_events",
614
+ ...where,
596
615
  repository: /* @__PURE__ */ __name(() => BufferedEventRepository, "repository"),
597
616
  // `(name, publishedAt)` serves both `listBufferedEvents`'s name-scoped scan and its oldest-first
598
617
  // ordering in one index.
@@ -632,6 +651,7 @@ function durableEntities(options = {}) {
632
651
  const signalIds = new EntitySchema({
633
652
  class: SignalIdEntity,
634
653
  tableName: "durable_signal_ids",
654
+ ...where,
635
655
  repository: /* @__PURE__ */ __name(() => SignalIdRepository, "repository"),
636
656
  // The expired-id sweep (`expires_at <= now`).
637
657
  indexes: [
@@ -662,6 +682,7 @@ function durableEntities(options = {}) {
662
682
  const schedules = new EntitySchema({
663
683
  class: ScheduleEntity,
664
684
  tableName: "durable_schedules",
685
+ ...where,
665
686
  repository: /* @__PURE__ */ __name(() => ScheduleRepository, "repository"),
666
687
  // The poll's "due by T" scan: `paused = false AND next_fire_at <= T ORDER BY next_fire_at`.
667
688
  indexes: [
@@ -806,6 +827,7 @@ function mikroOrmSchemaRepairWarning(repairs) {
806
827
  ].join(" ");
807
828
  }
808
829
  __name(mikroOrmSchemaRepairWarning, "mikroOrmSchemaRepairWarning");
830
+ var ALTER_TABLE_PREFIX = /^alter\s+table\s+(?:[`"']?[\w$]+[`"']?\.)?[`"']?[\w$]+[`"']?\s*/i;
809
831
  function unquote(identifier) {
810
832
  return identifier.replace(/^[`"']|[`"']$/g, "");
811
833
  }
@@ -822,7 +844,7 @@ function describeDurableStatement(statement) {
822
844
  if (/^alter\s+table\b/i.test(statement)) {
823
845
  const out = [];
824
846
  let other = false;
825
- for (const action of splitTopLevel(statement.replace(/^alter\s+table\s+[`"']?[\w$]+[`"']?\s*/i, ""))) {
847
+ for (const action of splitTopLevel(statement.replace(ALTER_TABLE_PREFIX, ""))) {
826
848
  const index = action.match(/^add\s+(?:unique\s+|fulltext\s+)?(?:index|key)\s+([`"']?[\w$]+[`"']?)/i);
827
849
  const constraint = action.match(/^add\s+constraint\s+([`"']?[\w$]+[`"']?)/i);
828
850
  const column = action.match(/^add\s+(?:column\s+)?([`"']?[\w$]+[`"']?)/i);
@@ -842,6 +864,11 @@ function describeDurableStatement(statement) {
842
864
  ];
843
865
  }
844
866
  __name(describeDurableStatement, "describeDurableStatement");
867
+ function inDurableSchema(statement, where) {
868
+ const match = statement.match(/^(?:create\s+(?:unique\s+)?index\s+.+?\s+on\s+|(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?)(?:[`"']?([\w$]+)[`"']?\.)?[`"']?[\w$]+[`"']?/i);
869
+ return match?.[1] === where.schema;
870
+ }
871
+ __name(inDurableSchema, "inDurableSchema");
845
872
  function splitTopLevel(text) {
846
873
  const parts = [];
847
874
  let depth = 0;
@@ -872,7 +899,7 @@ function compareStrings(a, b) {
872
899
  }
873
900
  __name(compareStrings, "compareStrings");
874
901
  function targetTable(statement) {
875
- const match = statement.match(/^(?:create\s+(?:unique\s+)?index\s+.+?\s+on\s+|(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?)[`"']?([\w$]+)[`"']?/i);
902
+ const match = statement.match(/^(?:create\s+(?:unique\s+)?index\s+.+?\s+on\s+|(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?)(?:[`"']?[\w$]+[`"']?\.)?[`"']?([\w$]+)[`"']?/i);
876
903
  return match?.[1]?.toLowerCase();
877
904
  }
878
905
  __name(targetTable, "targetTable");
@@ -941,19 +968,64 @@ function canonicalize(value) {
941
968
  return JSON.stringify(value);
942
969
  }
943
970
  __name(canonicalize, "canonicalize");
944
- function createMarkerTableSql() {
945
- return `create table if not exists ${MARKER_TABLE} (id varchar(32) not null primary key, fingerprint varchar(64) not null, applied_at bigint not null)`;
971
+ function durableTableSchema(orm, configured) {
972
+ const wanted = durableSchemaName(configured);
973
+ const runs = [
974
+ ...orm.getMetadata().getAll().values()
975
+ ].find((meta) => meta.class === WorkflowRunEntity || meta.tableName === "durable_workflow_runs");
976
+ const metaSchema2 = runs?.schema;
977
+ const registered = metaSchema2 && metaSchema2 !== "*" ? metaSchema2 : void 0;
978
+ const schema = wanted ?? registered;
979
+ if (schema !== void 0 && detectSqlDialect(orm) === "sqlite") {
980
+ throw new Error(`[nestjs-durable] store-mikro-orm: the schema option (${JSON.stringify(schema)}) is not supported on SQLite, which has no schemas. Remove it from the store options and from durableEntities().`);
981
+ }
982
+ if (wanted !== void 0 && wanted !== registered) {
983
+ throw new Error(`[nestjs-durable] store-mikro-orm: the store's schema is ${JSON.stringify(wanted)}, but the durable entities were registered ${registered === void 0 ? "without one" : `with ${JSON.stringify(registered)}`}. Register durableEntities({ schema: ${JSON.stringify(wanted)} }) in your MikroORM config.`);
984
+ }
985
+ return schema;
986
+ }
987
+ __name(durableTableSchema, "durableTableSchema");
988
+ function durableLocation(orm, configured) {
989
+ const schema = durableTableSchema(orm, configured);
990
+ const platform = orm.em.getPlatform();
991
+ const quote = /* @__PURE__ */ __name((id) => platform.quoteIdentifier(id), "quote");
992
+ return {
993
+ schema,
994
+ quote,
995
+ marker: schema === void 0 ? MARKER_TABLE : `${quote(schema)}.${quote(MARKER_TABLE)}`
996
+ };
997
+ }
998
+ __name(durableLocation, "durableLocation");
999
+ async function createSchemaIfMissing(orm, dialect, where) {
1000
+ if (where.schema === void 0) return;
1001
+ const connection = orm.em.getConnection();
1002
+ const rows = await connection.execute(dialect === "mysql" ? "select 1 as found from information_schema.schemata where schema_name = ?" : "select 1 as found from pg_namespace where nspname = ?", [
1003
+ where.schema
1004
+ ]);
1005
+ if (rows.length > 0) return;
1006
+ const kind = dialect === "mysql" ? "database" : "schema";
1007
+ try {
1008
+ await connection.execute(`create ${kind} if not exists ${where.quote(where.schema)}`);
1009
+ } catch (err) {
1010
+ throw new Error(`[nestjs-durable] store-mikro-orm could not create the ${kind} "${where.schema}" for the durable tables. Create it ahead of time, or grant this role ${dialect === "mysql" ? "CREATE" : "CREATE on the database (GRANT CREATE ON DATABASE <db> TO <role>)"}. Cause: ${err.message}`, {
1011
+ cause: err
1012
+ });
1013
+ }
1014
+ }
1015
+ __name(createSchemaIfMissing, "createSchemaIfMissing");
1016
+ function createMarkerTableSql(marker) {
1017
+ return `create table if not exists ${marker} (id varchar(32) not null primary key, fingerprint varchar(64) not null, applied_at bigint not null)`;
946
1018
  }
947
1019
  __name(createMarkerTableSql, "createMarkerTableSql");
948
- async function readStoredFingerprint(orm) {
949
- const rows = await orm.em.getConnection().execute(`select fingerprint from ${MARKER_TABLE} where id = ?`, [
1020
+ async function readStoredFingerprint(orm, where) {
1021
+ const rows = await orm.em.getConnection().execute(`select fingerprint from ${where.marker} where id = ?`, [
950
1022
  MARKER_ROW_ID
951
1023
  ]);
952
1024
  return rows[0]?.fingerprint ?? void 0;
953
1025
  }
954
1026
  __name(readStoredFingerprint, "readStoredFingerprint");
955
- async function writeFingerprint(orm, dialect, fingerprint) {
956
- const upsert = dialect === "mysql" ? `insert into ${MARKER_TABLE} (id, fingerprint, applied_at) values (?, ?, ?) on duplicate key update fingerprint = values(fingerprint), applied_at = values(applied_at)` : `insert into ${MARKER_TABLE} (id, fingerprint, applied_at) values (?, ?, ?) on conflict (id) do update set fingerprint = excluded.fingerprint, applied_at = excluded.applied_at`;
1027
+ async function writeFingerprint(orm, dialect, fingerprint, where) {
1028
+ const upsert = dialect === "mysql" ? `insert into ${where.marker} (id, fingerprint, applied_at) values (?, ?, ?) on duplicate key update fingerprint = values(fingerprint), applied_at = values(applied_at)` : `insert into ${where.marker} (id, fingerprint, applied_at) values (?, ?, ?) on conflict (id) do update set fingerprint = excluded.fingerprint, applied_at = excluded.applied_at`;
957
1029
  await orm.em.getConnection().execute(upsert, [
958
1030
  MARKER_ROW_ID,
959
1031
  fingerprint,
@@ -961,12 +1033,17 @@ async function writeFingerprint(orm, dialect, fingerprint) {
961
1033
  ]);
962
1034
  }
963
1035
  __name(writeFingerprint, "writeFingerprint");
964
- async function acquireSchemaLock(orm, dialect) {
1036
+ function schemaLockName(where) {
1037
+ return where.schema === void 0 ? SCHEMA_LOCK_NAME : `${SCHEMA_LOCK_NAME}:${where.schema}`;
1038
+ }
1039
+ __name(schemaLockName, "schemaLockName");
1040
+ async function acquireSchemaLock(orm, dialect, where) {
1041
+ const name = schemaLockName(where);
965
1042
  try {
966
1043
  if (dialect === "mysql") {
967
- await orm.em.getConnection().execute(`select get_lock('${SCHEMA_LOCK_NAME}', 10)`);
1044
+ await orm.em.getConnection().execute(`select get_lock('${name}', 10)`);
968
1045
  } else if (dialect === "postgres") {
969
- await orm.em.getConnection().execute(`select pg_advisory_lock(hashtext('${SCHEMA_LOCK_NAME}'))`);
1046
+ await orm.em.getConnection().execute(`select pg_advisory_lock(hashtext('${name}'))`);
970
1047
  }
971
1048
  } catch (err) {
972
1049
  const message = err instanceof Error ? err.message : String(err);
@@ -974,12 +1051,13 @@ async function acquireSchemaLock(orm, dialect) {
974
1051
  }
975
1052
  }
976
1053
  __name(acquireSchemaLock, "acquireSchemaLock");
977
- async function releaseSchemaLock(orm, dialect) {
1054
+ async function releaseSchemaLock(orm, dialect, where) {
1055
+ const name = schemaLockName(where);
978
1056
  try {
979
1057
  if (dialect === "mysql") {
980
- await orm.em.getConnection().execute(`select release_lock('${SCHEMA_LOCK_NAME}')`);
1058
+ await orm.em.getConnection().execute(`select release_lock('${name}')`);
981
1059
  } else if (dialect === "postgres") {
982
- await orm.em.getConnection().execute(`select pg_advisory_unlock(hashtext('${SCHEMA_LOCK_NAME}'))`);
1060
+ await orm.em.getConnection().execute(`select pg_advisory_unlock(hashtext('${name}'))`);
983
1061
  }
984
1062
  } catch {
985
1063
  }
@@ -988,35 +1066,38 @@ __name(releaseSchemaLock, "releaseSchemaLock");
988
1066
  async function ensureMikroOrmDurableSchema(orm, options = {}) {
989
1067
  const logger = options.logger ?? console;
990
1068
  const dialect = detectSqlDialect(orm);
991
- await orm.em.getConnection().execute(createMarkerTableSql());
1069
+ const where = durableLocation(orm, options.schema);
1070
+ await createSchemaIfMissing(orm, dialect, where);
1071
+ await orm.em.getConnection().execute(createMarkerTableSql(where.marker));
992
1072
  const expected = computeExpectedFingerprint(orm, DURABLE_TABLE_NAMES);
993
- const stored = await readStoredFingerprint(orm);
1073
+ const stored = await readStoredFingerprint(orm, where);
994
1074
  if (stored === expected) {
995
1075
  return;
996
1076
  }
997
- await acquireSchemaLock(orm, dialect);
1077
+ await acquireSchemaLock(orm, dialect, where);
998
1078
  try {
999
- if (await readStoredFingerprint(orm) === expected) {
1079
+ if (await readStoredFingerprint(orm, where) === expected) {
1000
1080
  return;
1001
1081
  }
1002
1082
  const limit = options.blockingAlterRowLimit ?? DEFAULT_BLOCKING_ALTER_ROW_LIMIT;
1003
- const { repairs, freshInstall, deferred } = await healDurableSchema(orm, dialect, limit);
1004
- if (deferred.length === 0) await writeFingerprint(orm, dialect, expected);
1083
+ const { repairs, freshInstall, deferred } = await healDurableSchema(orm, dialect, limit, where);
1084
+ if (deferred.length === 0) await writeFingerprint(orm, dialect, expected, where);
1005
1085
  if (repairs.length > 0 && !freshInstall) logger.warn(mikroOrmSchemaRepairWarning(repairs));
1006
1086
  if (deferred.length > 0) logger.warn(mikroOrmDeferredAlterWarning(deferred, limit));
1007
1087
  } finally {
1008
- await releaseSchemaLock(orm, dialect);
1088
+ await releaseSchemaLock(orm, dialect, where);
1009
1089
  }
1010
1090
  }
1011
1091
  __name(ensureMikroOrmDurableSchema, "ensureMikroOrmDurableSchema");
1012
- async function healDurableSchema(orm, dialect, blockingAlterRowLimit) {
1092
+ async function healDurableSchema(orm, dialect, blockingAlterRowLimit, where) {
1013
1093
  const sql = await orm.schema.getUpdateSchemaSQL({
1014
1094
  safe: true
1015
1095
  });
1016
- const ours = mergeColumnTypeChanges(sql.split(";").map((statement) => statement.trim()).filter((statement) => {
1096
+ const diff = sql.split(";").map((statement) => statement.trim()).filter((statement) => {
1017
1097
  const table = targetTable(statement);
1018
- return table !== void 0 && DURABLE_TABLE_NAMES.has(table);
1019
- }));
1098
+ return table !== void 0 && DURABLE_TABLE_NAMES.has(table) && inDurableSchema(statement, where);
1099
+ });
1100
+ const ours = mergeColumnTypeChanges(dialect === "mysql" && where.schema !== void 0 ? await narrowMysqlSchemaDiff(orm, where.schema, diff) : diff);
1020
1101
  const connection = orm.em.getConnection();
1021
1102
  const created = new Set(ours.filter((statement) => /^create\s+table\b/i.test(statement)).map((statement) => targetTable(statement)));
1022
1103
  const repairs = [];
@@ -1024,7 +1105,7 @@ async function healDurableSchema(orm, dialect, blockingAlterRowLimit) {
1024
1105
  for (const statement of ours) {
1025
1106
  const table = targetTable(statement);
1026
1107
  if (dialect === "mysql" && !created.has(table) && isColumnTypeChange(statement)) {
1027
- const rows = await estimatedRowCount(orm, table);
1108
+ const rows = await estimatedRowCount(orm, table, where);
1028
1109
  if (rows > blockingAlterRowLimit) {
1029
1110
  deferred.push({
1030
1111
  table,
@@ -1046,7 +1127,7 @@ async function healDurableSchema(orm, dialect, blockingAlterRowLimit) {
1046
1127
  console.warn(`[nestjs-durable-store-mikro-orm] skipped a non-structural durable-schema statement that failed; the column is left as-is (functional) \u2014 repair the data out of band to converge its type. Statement: ${statement} \u2014 ${message}`);
1047
1128
  }
1048
1129
  }
1049
- const converted = await alignDurableCollation(orm);
1130
+ const converted = await alignDurableCollation(orm, where);
1050
1131
  for (const { table, from, to } of converted) {
1051
1132
  if (!created.has(table)) repairs.push(`converted ${table} collation from ${from} to ${to}`);
1052
1133
  }
@@ -1060,6 +1141,40 @@ async function healDurableSchema(orm, dialect, blockingAlterRowLimit) {
1060
1141
  };
1061
1142
  }
1062
1143
  __name(healDurableSchema, "healDurableSchema");
1144
+ async function narrowMysqlSchemaDiff(orm, schema, diff) {
1145
+ const connection = orm.em.getConnection();
1146
+ const columns = await connection.execute("select table_name as table_name, column_name as column_name from information_schema.columns where table_schema = ?", [
1147
+ schema
1148
+ ]);
1149
+ const indexes = await connection.execute("select distinct table_name as table_name, index_name as index_name from information_schema.statistics where table_schema = ?", [
1150
+ schema
1151
+ ]);
1152
+ const tables = new Set(columns.map((c) => c.table_name.toLowerCase()));
1153
+ const hasColumn = new Set(columns.map((c) => `${c.table_name}.${c.column_name}`.toLowerCase()));
1154
+ const hasIndex = new Set(indexes.map((i) => `${i.table_name}.${i.index_name}`.toLowerCase()));
1155
+ const out = [];
1156
+ for (const statement of diff) {
1157
+ const table = targetTable(statement);
1158
+ if (!tables.has(table)) {
1159
+ out.push(statement);
1160
+ continue;
1161
+ }
1162
+ if (/^create\s+table\b/i.test(statement)) {
1163
+ const open = statement.indexOf("(");
1164
+ const close = statement.lastIndexOf(")");
1165
+ const prefix = statement.slice(0, open).replace(/^create\s+table\s+/i, "").trim();
1166
+ for (const definition of splitTopLevel(statement.slice(open + 1, close))) {
1167
+ const column = definition.match(/^[`"]([^`"]+)[`"]\s/);
1168
+ if (column?.[1] && !hasColumn.has(`${table}.${column[1]}`.toLowerCase())) out.push(`alter table ${prefix} add column ${definition}`);
1169
+ }
1170
+ continue;
1171
+ }
1172
+ const index = statement.match(/\badd\s+(?:unique\s+|fulltext\s+)?(?:index|key)\s+[`"]([^`"]+)[`"]/i);
1173
+ if (index?.[1] && !hasIndex.has(`${table}.${index[1]}`.toLowerCase())) out.push(statement);
1174
+ }
1175
+ return out;
1176
+ }
1177
+ __name(narrowMysqlSchemaDiff, "narrowMysqlSchemaDiff");
1063
1178
  function mergeColumnTypeChanges(statements) {
1064
1179
  const merged = [];
1065
1180
  const at = /* @__PURE__ */ new Map();
@@ -1069,7 +1184,7 @@ function mergeColumnTypeChanges(statements) {
1069
1184
  merged.push(statement);
1070
1185
  continue;
1071
1186
  }
1072
- const actions = statement.replace(/^alter\s+table\s+[`"']?[\w$]+[`"']?\s*/i, "");
1187
+ const actions = statement.replace(ALTER_TABLE_PREFIX, "");
1073
1188
  const index = at.get(table);
1074
1189
  if (index === void 0) {
1075
1190
  at.set(table, merged.length);
@@ -1083,12 +1198,15 @@ function mergeColumnTypeChanges(statements) {
1083
1198
  __name(mergeColumnTypeChanges, "mergeColumnTypeChanges");
1084
1199
  function isColumnTypeChange(statement) {
1085
1200
  if (!/^alter\s+table\b/i.test(statement)) return false;
1086
- const actions = splitTopLevel(statement.replace(/^alter\s+table\s+[`"']?[\w$]+[`"']?\s*/i, ""));
1201
+ const actions = splitTopLevel(statement.replace(ALTER_TABLE_PREFIX, ""));
1087
1202
  return actions.length > 0 && actions.every((action) => /^modify\b/i.test(action));
1088
1203
  }
1089
1204
  __name(isColumnTypeChange, "isColumnTypeChange");
1090
- async function estimatedRowCount(orm, table) {
1091
- const rows = await orm.em.getConnection().execute("select table_rows as table_rows from information_schema.tables where table_schema = database() and table_name = ? limit 1", [
1205
+ async function estimatedRowCount(orm, table, where) {
1206
+ const rows = await orm.em.getConnection().execute(`select table_rows as table_rows from information_schema.tables where table_schema = ${where.schema === void 0 ? "database()" : "?"} and table_name = ? limit 1`, where.schema === void 0 ? [
1207
+ table
1208
+ ] : [
1209
+ where.schema,
1092
1210
  table
1093
1211
  ]);
1094
1212
  return Number(rows[0]?.table_rows ?? 0);
@@ -1098,7 +1216,7 @@ function isSafeSqlIdentifier(value) {
1098
1216
  return /^[A-Za-z0-9_]+$/.test(value);
1099
1217
  }
1100
1218
  __name(isSafeSqlIdentifier, "isSafeSqlIdentifier");
1101
- async function alignDurableCollation(orm) {
1219
+ async function alignDurableCollation(orm, where) {
1102
1220
  const converted = [];
1103
1221
  const platform = String(orm.em.getPlatform().constructor.name).toLowerCase();
1104
1222
  if (!platform.includes("mysql") && !platform.includes("maria")) {
@@ -1115,14 +1233,17 @@ async function alignDurableCollation(orm) {
1115
1233
  const connection = orm.em.getConnection();
1116
1234
  for (const table of DURABLE_TABLE_NAMES) {
1117
1235
  try {
1118
- const rows = await connection.execute("select table_collation as collation from information_schema.tables where table_schema = database() and table_name = ? limit 1", [
1236
+ const rows = await connection.execute(`select table_collation as collation from information_schema.tables where table_schema = ${where.schema === void 0 ? "database()" : "?"} and table_name = ? limit 1`, where.schema === void 0 ? [
1237
+ table
1238
+ ] : [
1239
+ where.schema,
1119
1240
  table
1120
1241
  ]);
1121
1242
  const current = rows[0]?.collation;
1122
1243
  if (current == null || current === collate) {
1123
1244
  continue;
1124
1245
  }
1125
- await connection.execute(`alter table \`${table}\` convert to character set ${charset} collate ${collate}`);
1246
+ await connection.execute(`alter table ${where.schema === void 0 ? `\`${table}\`` : `${where.quote(where.schema)}.${where.quote(table)}`} convert to character set ${charset} collate ${collate}`);
1126
1247
  converted.push({
1127
1248
  table,
1128
1249
  from: current,
@@ -1138,6 +1259,14 @@ async function alignDurableCollation(orm) {
1138
1259
  __name(alignDurableCollation, "alignDurableCollation");
1139
1260
 
1140
1261
  // src/mikro-orm-state-store.ts
1262
+ function metaSchema(meta) {
1263
+ return meta.schema && meta.schema !== "*" ? meta.schema : void 0;
1264
+ }
1265
+ __name(metaSchema, "metaSchema");
1266
+ function tableRef(quote, table, schema) {
1267
+ return schema === void 0 ? quote(table) : `${quote(schema)}.${quote(table)}`;
1268
+ }
1269
+ __name(tableRef, "tableRef");
1141
1270
  var RETENTION_EXCLUDED = [
1142
1271
  LIFECYCLE_REGISTRY_WORKFLOW
1143
1272
  ];
@@ -1164,6 +1293,7 @@ var MikroOrmStateStore = class _MikroOrmStateStore {
1164
1293
  } catch {
1165
1294
  return;
1166
1295
  }
1296
+ durableTableSchema(orm, opts.schema);
1167
1297
  const dialect = platform.includes("postgre") ? "postgres" : platform.includes("mysql") ? "mysql" : void 0;
1168
1298
  if (!dialect) return;
1169
1299
  const fast = new MikroOrmRoundTrips(() => this.orm.em.fork(), dialect, this.scopeNamespace, this);
@@ -1202,7 +1332,8 @@ var MikroOrmStateStore = class _MikroOrmStateStore {
1202
1332
  async ensureSchema() {
1203
1333
  await ensureMikroOrmDurableSchema(this.orm, {
1204
1334
  logger: this.opts.schemaLogger,
1205
- blockingAlterRowLimit: this.opts.schemaBlockingAlterRowLimit
1335
+ blockingAlterRowLimit: this.opts.schemaBlockingAlterRowLimit,
1336
+ schema: this.opts.schema
1206
1337
  });
1207
1338
  }
1208
1339
  async tryAdmitSingleton(runId, tag, workflow, limit, retryWakeAt) {
@@ -1938,7 +2069,7 @@ var MikroOrmStateStore = class _MikroOrmStateStore {
1938
2069
  const cols = this.attributeColumns(em);
1939
2070
  const idCol = meta.properties.id?.fieldNames?.[0] ?? "id";
1940
2071
  const a = quote("a");
1941
- const join = `${quote(cols.table)} as ${a} join (${runs}) as ${quote("r")} on ${a}.${quote(cols.runId)} = ${quote("r")}.${quote(idCol)}`;
2072
+ const join = `${tableRef(quote, cols.table, cols.schema)} as ${a} join (${runs}) as ${quote("r")} on ${a}.${quote(cols.runId)} = ${quote("r")}.${quote(idCol)}`;
1942
2073
  if (axis.field === "attributeKey") {
1943
2074
  return {
1944
2075
  source: join,
@@ -1995,7 +2126,7 @@ var MikroOrmStateStore = class _MikroOrmStateStore {
1995
2126
  return `${quote("a")}.${quote(col)} ${comparator} ${literal}`;
1996
2127
  });
1997
2128
  if (comparisons.length === 0) return "1 = 0";
1998
- const a = quote(cols.table);
2129
+ const a = tableRef(quote, cols.table, cols.schema);
1999
2130
  const sub = quote("a");
2000
2131
  const outerId = `${quote(alias)}.${quote(cols.runPk)}`;
2001
2132
  const match = comparisons.length === 1 ? comparisons[0] : `(${comparisons.join(" OR ")})`;
@@ -2011,6 +2142,7 @@ var MikroOrmStateStore = class _MikroOrmStateStore {
2011
2142
  const runPk = runMeta.properties.id?.fieldNames?.[0] ?? "id";
2012
2143
  return {
2013
2144
  table: meta.tableName,
2145
+ schema: metaSchema(meta),
2014
2146
  runId: field("runId"),
2015
2147
  runPk,
2016
2148
  key: field("key"),
@@ -2222,7 +2354,7 @@ var MikroOrmStateStore = class _MikroOrmStateStore {
2222
2354
  where += ` and ${c("parallelGroup")} = ?`;
2223
2355
  params.push(opts.group);
2224
2356
  }
2225
- const sql = `select ${c("parallelGroup")} as ${quote("grp")}, ${c("status")} as ${quote("status")}, ${nameKind} as ${quote("name_kind")}, count(*) as ${quote("n")}, min(${c("seq")}) as ${quote("min_seq")}, max(${c("seq")}) as ${quote("max_seq")}, min(${c("name")}) as ${quote("min_name")}, max(${c("name")}) as ${quote("max_name")}, min(coalesce(${c("enqueuedAt")}, ${c("startedAt")})) as ${quote("min_enqueued_at")}, min(${c("startedAt")}) as ${quote("min_started_at")}, max(${c("startedAt")}) as ${quote("max_started_at")}, max(${c("finishedAt")}) as ${quote("max_finished_at")}, sum(${c("attempts")}) as ${quote("sum_attempts")} from ${quote(meta.tableName)} where ${where} group by ${c("parallelGroup")}, ${c("status")}, ${nameKind}`;
2357
+ const sql = `select ${c("parallelGroup")} as ${quote("grp")}, ${c("status")} as ${quote("status")}, ${nameKind} as ${quote("name_kind")}, count(*) as ${quote("n")}, min(${c("seq")}) as ${quote("min_seq")}, max(${c("seq")}) as ${quote("max_seq")}, min(${c("name")}) as ${quote("min_name")}, max(${c("name")}) as ${quote("max_name")}, min(coalesce(${c("enqueuedAt")}, ${c("startedAt")})) as ${quote("min_enqueued_at")}, min(${c("startedAt")}) as ${quote("min_started_at")}, max(${c("startedAt")}) as ${quote("max_started_at")}, max(${c("finishedAt")}) as ${quote("max_finished_at")}, sum(${c("attempts")}) as ${quote("sum_attempts")} from ${tableRef(quote, meta.tableName, metaSchema(meta))} where ${where} group by ${c("parallelGroup")}, ${c("status")}, ${nameKind}`;
2226
2358
  const rows = await em.getConnection().execute(sql, params);
2227
2359
  const date = aggregateDateReader(em);
2228
2360
  return rows.map((row) => ({
@@ -2906,7 +3038,8 @@ var MikroOrmRoundTrips = class MikroOrmRoundTrips2 {
2906
3038
  return this.q(em, this.field(em, entity, property));
2907
3039
  }
2908
3040
  table(em, entity) {
2909
- return this.q(em, this.meta(em, entity).tableName);
3041
+ const meta = this.meta(em, entity);
3042
+ return tableRef((id) => this.q(em, id), meta.tableName, metaSchema(meta));
2910
3043
  }
2911
3044
  /**
2912
3045
  * `value` as a raw-SQL parameter for `property` (its custom type's conversion, if any).
@@ -2969,8 +3102,11 @@ var MikroOrmRoundTrips = class MikroOrmRoundTrips2 {
2969
3102
  }
2970
3103
  async cpType(em, property) {
2971
3104
  const field = this.field(em, StepCheckpointEntity, property);
2972
- this.cpTypes ??= this.run(em, "SELECT column_name AS name, data_type AS type FROM information_schema.columns WHERE table_name = ? AND table_schema = current_schema()", [
2973
- this.meta(em, StepCheckpointEntity).tableName
3105
+ this.cpTypes ??= this.run(em, metaSchema(this.meta(em, StepCheckpointEntity)) === void 0 ? "SELECT column_name AS name, data_type AS type FROM information_schema.columns WHERE table_name = ? AND table_schema = current_schema()" : "SELECT column_name AS name, data_type AS type FROM information_schema.columns WHERE table_name = ? AND table_schema = ?", [
3106
+ this.meta(em, StepCheckpointEntity).tableName,
3107
+ ...metaSchema(this.meta(em, StepCheckpointEntity)) === void 0 ? [] : [
3108
+ metaSchema(this.meta(em, StepCheckpointEntity))
3109
+ ]
2974
3110
  ]).then((out) => new Map(this.rows(out).map((r) => [
2975
3111
  String(r.name),
2976
3112
  String(r.type)
@@ -3135,6 +3271,8 @@ export {
3135
3271
  WorkflowRunRepository,
3136
3272
  durableEntities,
3137
3273
  durableManagedTables,
3274
+ durableSchemaName,
3275
+ durableTableSchema,
3138
3276
  ensureMikroOrmDurableSchema,
3139
3277
  mikroOrmDeferredAlterWarning,
3140
3278
  mikroOrmSchemaRepairWarning