@decohere/data-mikro-orm 0.0.1-dev.20261110.284 → 0.0.1-dev.20261110.311

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/README.md CHANGED
@@ -9,19 +9,27 @@ builder.use(
9
9
  mikroOrm({
10
10
  entities: [OrderSchema, LineSchema],
11
11
  repositories: [OrderRepository],
12
- bootstrap: postgres.bootstrap, // from @decohere/data-postgres
12
+ database: postgres, // from @decohere/data-postgres
13
+ migrations, // from ./migrations/index.js
13
14
  outbox: toOutboxMessage,
14
15
  }),
15
16
  );
16
17
  ```
17
18
 
18
- `mikroOrm()` reads the `database` config section, like `typeOrm()`. For each data source it:
19
+ `mikroOrm()` reads the `database` config section, like `typeOrm()`. When the app is built, for each data source it:
19
20
 
20
- - checks each data source's `auth` and `synchronize`, and creates its database, least-privilege roles and schema when the config asks, with the `bootstrap` you pass (`postgres.bootstrap` from `@decohere/data-postgres`);
21
+ - checks the data source's `auth`, `synchronize` and `migrateOnStart`, and creates its database, least-privilege roles and schema when the config asks, with the `database` you pass;
21
22
  - opens one MikroORM instance as the app role, named for the app in `application_name`;
23
+ - registers a unit of work per request (`@injectUnitOfWork()`), the instance itself (`@injectMikroOrm()`) and a readiness check;
24
+ - registers the data source's migrations and schema diff for the db commands, when given a `database`.
25
+
26
+ When the app starts, before hosted services and the server, it:
27
+
28
+ - applies pending migrations when `migrateOnStart` is on (development only);
22
29
  - creates missing tables when `synchronize` is on (development only), never dropping any;
23
- - runs `seed(orm)` when `seed` is on;
24
- - registers a unit of work per request (`@injectUnitOfWork()`), the instance itself (`@injectMikroOrm()`) and a readiness check.
30
+ - runs `seed(orm)` when `seed` is on.
31
+
32
+ `db generate` takes MikroORM's schema diff, connected as the migrate role. MikroORM proposes dropping every table it sees and doesn't map, so the role's reach to its own schema is what keeps another app's tables out of the diff. The history table is skipped by name, and `create schema` and `drop schema` are left out: schemas are the bootstrap's. `synchronize` leaves out `create schema` for the same reason: the app role may not run it even when the schema exists.
25
33
 
26
34
  The container closes the instance when the app stops, after hosted services. Postgres only. Outside a plugin, `new MikroOrmUnitOfWork(orm.em, { outbox })` gives the same unit of work.
27
35
 
@@ -1,17 +1,18 @@
1
1
  import { ReadinessCheckToken } from "@decohere/core/hosting";
2
- import { DatabaseConfig, DataConfigurationError, dataSources } from "@decohere/data";
2
+ import { DatabaseConfig, DataConfigurationError, dataSources, MigrationTargetToken } from "@decohere/data";
3
3
  import { scribe } from "@decohere/scribe";
4
4
  import { MikroORM } from "@mikro-orm/postgresql";
5
5
  import { mikroOrmToken } from "./inject-mikro-orm.js";
6
6
  import { MikroOrmUnitOfWork } from "./mikro-orm.unit-of-work.js";
7
+ const HISTORY_TABLE = "decohere_migrations";
7
8
  export class MikroOrmModule {
8
- /** Bootstraps and opens a MikroORM instance per data source. Returns the names it registered them under. */ async configure(options) {
9
+ /** Bootstraps and opens a MikroORM instance per data source, and registers what each one serves. */ async configure(options) {
9
10
  const { applicationName, databaseConfig, moduleConfigurations, containerBuilder } = options;
10
11
  const resolved = dataSources.resolve(databaseConfig, moduleConfigurations);
11
12
  // Once, before any instance connects: data sources sharing a database must not race to create it.
12
13
  await dataSources.prepare(resolved.map((r)=>r.connectionInfo), {
13
14
  applicationName,
14
- bootstrap: moduleConfigurations.find((m)=>m.bootstrap)?.bootstrap
15
+ bootstrap: moduleConfigurations.find((m)=>m.database)?.database?.bootstrap
15
16
  });
16
17
  return Promise.all(resolved.map(async ({ name, connectionInfo, module })=>{
17
18
  const orm = await this.open(applicationName, name, connectionInfo, module);
@@ -23,7 +24,19 @@ export class MikroOrmModule {
23
24
  for (const repository of module.repositories ?? []){
24
25
  containerBuilder.registerRequestScoped(repository);
25
26
  }
26
- return name;
27
+ const migrations = migrationTarget(applicationName, connectionInfo, module);
28
+ if (migrations != null) {
29
+ containerBuilder.registerSingleton(MigrationTargetToken, migrations);
30
+ }
31
+ return {
32
+ name,
33
+ starting: {
34
+ connection: connectionInfo,
35
+ migrations,
36
+ synchronize: ()=>synchronize(orm),
37
+ seed: async ()=>module.seed?.(orm)
38
+ }
39
+ };
27
40
  }));
28
41
  }
29
42
  async open(applicationName, name, connection, module) {
@@ -31,7 +44,7 @@ export class MikroOrmModule {
31
44
  throw new DataConfigurationError(`Data source ${connection.name}: the MikroORM provider supports postgres, not ${connection.provider}`);
32
45
  }
33
46
  const log = scribe.logger(`MikroORM:${String(name)}`);
34
- const orm = await MikroORM.init({
47
+ return MikroORM.init({
35
48
  host: connection.host,
36
49
  port: connection.port,
37
50
  dbName: connection.database,
@@ -48,11 +61,24 @@ export class MikroOrmModule {
48
61
  ],
49
62
  logger: (message)=>log.debug(message)
50
63
  });
51
- if (connection.synchronize) await synchronize(orm);
52
- if (connection.seed) await module.seed?.(orm);
53
- return orm;
54
64
  }
55
65
  }
66
+ function migrationTarget(applicationName, connection, module) {
67
+ if (module.database == null) return undefined;
68
+ return {
69
+ dataSource: connection.name,
70
+ source: {
71
+ connection,
72
+ migrations: module.migrations ?? [],
73
+ applicationName
74
+ },
75
+ migrator: module.database.migrator,
76
+ diff: ()=>diff(applicationName, connection, module.entities)
77
+ };
78
+ }
79
+ /** MikroORM's statements one per entry, without `create schema` or `drop schema`: schemas are the bootstrap's. */ function statements(sql) {
80
+ return sql.split(/;\n/).map((statement)=>statement.trim().replace(/;$/, "")).filter((statement)=>statement.length > 0 && !/^(create|drop) schema\b/i.test(statement));
81
+ }
56
82
  /**
57
83
  * Bring the tables up to the mappings, safely: add what they need, never drop what they don't name.
58
84
  * MikroORM starts the update with `create schema`, which the app role may not run even when the
@@ -63,8 +89,41 @@ export class MikroOrmModule {
63
89
  dropTables: false,
64
90
  wrap: false
65
91
  });
66
- const statements = sql.split(/;\n/).map((statement)=>statement.trim().replace(/;$/, "")).filter((statement)=>statement.length > 0 && !/^create schema\b/i.test(statement));
67
- for (const statement of statements)await orm.schema.execute(statement);
92
+ for (const statement of statements(sql))await orm.schema.execute(statement);
93
+ }
94
+ /**
95
+ * MikroORM's schema diff, connected as the migrate role. That role sees only its own schema, so the
96
+ * diff can't propose dropping another app's tables: MikroORM drops every table it sees and doesn't map.
97
+ * The history table is skipped by name.
98
+ */ async function diff(applicationName, connection, entities) {
99
+ const orm = await MikroORM.init({
100
+ host: connection.host,
101
+ port: connection.port,
102
+ dbName: connection.database,
103
+ user: connection.migrateUsername || connection.username,
104
+ password: connection.migrateUsername ? connection.migratePassword : connection.password,
105
+ schema: connection.schema,
106
+ entities,
107
+ driverOptions: {
108
+ application_name: applicationName
109
+ },
110
+ schemaGenerator: {
111
+ skipTables: [
112
+ HISTORY_TABLE
113
+ ]
114
+ }
115
+ });
116
+ try {
117
+ const { up, down } = await orm.schema.getUpdateSchemaMigrationSQL({
118
+ wrap: false
119
+ });
120
+ return {
121
+ up: statements(up),
122
+ down: statements(down)
123
+ };
124
+ } finally{
125
+ await orm.close();
126
+ }
68
127
  }
69
128
  function readinessCheck(name, orm) {
70
129
  return {
@@ -79,10 +138,10 @@ function readinessCheck(name, orm) {
79
138
  }
80
139
  /** Connect to the databases in the `database` config section with MikroORM. Requires `config(...)` on the builder. */ export function mikroOrm(config) {
81
140
  return (builder)=>{
82
- const names = [];
141
+ const opened = [];
83
142
  builder.registerPreBuildStep(async (configService, containerBuilder)=>{
84
143
  const databaseConfig = await configService.get(DatabaseConfig);
85
- names.push(...await new MikroOrmModule().configure({
144
+ opened.push(...await new MikroOrmModule().configure({
86
145
  applicationName: builder.applicationName,
87
146
  databaseConfig,
88
147
  moduleConfigurations: Array.isArray(config) ? config : [
@@ -95,7 +154,13 @@ function readinessCheck(name, orm) {
95
154
  // root container own it, as one of its first, so it closes last: after hosted services
96
155
  // and the services that use it.
97
156
  builder.registerPostBuildStep((container)=>{
98
- for (const name of names)container.resolve(mikroOrmToken(name));
157
+ for (const { name } of opened)container.resolve(mikroOrmToken(name));
158
+ });
159
+ builder.registerStartStep(async (container)=>{
160
+ const log = scribe.logger("migrations");
161
+ for (const { starting } of opened){
162
+ await dataSources.start(starting, container, (line)=>log.info(line));
163
+ }
99
164
  });
100
165
  };
101
166
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decohere/data-mikro-orm",
3
- "version": "0.0.1-dev.20261110.284",
3
+ "version": "0.0.1-dev.20261110.311",
4
4
  "description": "MikroORM provider for @decohere/data: its own unit of work under data's contracts",
5
5
  "keywords": [
6
6
  "typescript",
@@ -31,10 +31,10 @@
31
31
  "test": "echo \"Error: no test specified\" && exit 1"
32
32
  },
33
33
  "dependencies": {
34
- "@decohere/core": "0.0.1-dev.20261110.284",
35
- "@decohere/crucible": "0.0.1-dev.20261110.284",
36
- "@decohere/data": "0.0.1-dev.20261110.284",
37
- "@decohere/scribe": "0.0.1-dev.20261110.284",
34
+ "@decohere/core": "0.0.1-dev.20261110.311",
35
+ "@decohere/crucible": "0.0.1-dev.20261110.311",
36
+ "@decohere/data": "0.0.1-dev.20261110.311",
37
+ "@decohere/scribe": "0.0.1-dev.20261110.311",
38
38
  "@mikro-orm/core": "^7.2.8",
39
39
  "@mikro-orm/postgresql": "^7.2.8"
40
40
  },
@@ -1,7 +1,7 @@
1
1
  import type { BuilderPlugin } from "@decohere/core/hosting";
2
2
  import type { Constructable } from "@decohere/core/reflection";
3
3
  import type { ContainerBuilder } from "@decohere/crucible";
4
- import { DatabaseConfig, type DataSourceBootstrap, type OutboxMapper } from "@decohere/data";
4
+ import { DatabaseConfig, type DatabaseSupport, type Migration, type OutboxMapper, type StartingDataSource } from "@decohere/data";
5
5
  import { type Options, MikroORM } from "@mikro-orm/postgresql";
6
6
  export type MikroOrmModuleConfig = {
7
7
  /** The data source's name in the `database` config. Required when there is more than one. */
@@ -9,11 +9,16 @@ export type MikroOrmModuleConfig = {
9
9
  /** The mappings: `defineEntity({ class, … })` results or `EntitySchema`s. */
10
10
  entities: NonNullable<Options["entities"]>;
11
11
  repositories?: Constructable[];
12
- /** Creates the database, roles and schema when the config asks: `postgres.bootstrap` from `@decohere/data-postgres`. */
13
- bootstrap?: DataSourceBootstrap;
12
+ /**
13
+ * The database's package: `postgres` from `@decohere/data-postgres`. It creates the database,
14
+ * roles and schema when the config asks, and runs migrations.
15
+ */
16
+ database?: DatabaseSupport;
17
+ /** The data source's migrations: `migrations` from its migrations folder's `index.ts`. */
18
+ migrations?: readonly Migration[];
14
19
  /** Writes the events aggregates raise to an outbox entity, in the same commit. */
15
20
  outbox?: OutboxMapper;
16
- /** Runs after connecting when the data source's `seed` is on. */
21
+ /** Runs when the app starts, after migrations, when the data source's `seed` is on. */
17
22
  seed?: (orm: MikroORM) => Promise<void>;
18
23
  };
19
24
  export type MikroOrmModuleOptions = {
@@ -22,9 +27,14 @@ export type MikroOrmModuleOptions = {
22
27
  moduleConfigurations: MikroOrmModuleConfig[];
23
28
  containerBuilder: ContainerBuilder;
24
29
  };
30
+ /** A data source the module opened: its container key, and what the app does with it on start. */
31
+ export type OpenedMikroOrm = {
32
+ name: string | symbol;
33
+ starting: StartingDataSource;
34
+ };
25
35
  export declare class MikroOrmModule {
26
- /** Bootstraps and opens a MikroORM instance per data source. Returns the names it registered them under. */
27
- configure(options: MikroOrmModuleOptions): Promise<(string | symbol)[]>;
36
+ /** Bootstraps and opens a MikroORM instance per data source, and registers what each one serves. */
37
+ configure(options: MikroOrmModuleOptions): Promise<OpenedMikroOrm[]>;
28
38
  private open;
29
39
  }
30
40
  /** Connect to the databases in the `database` config section with MikroORM. Requires `config(...)` on the builder. */