bazis 0.98.20 → 0.98.21

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.
@@ -232,7 +232,7 @@ export class CodexAppServerClient implements CodexClient {
232
232
  if (method === "account/updated") this.modelCache = undefined;
233
233
  }, () => { this.clearLogin(); this.modelCache = undefined; });
234
234
  const initialized = await client.request("initialize", {
235
- clientInfo: { name: "bazis", title: "Bazis", version: "0.98.20" }, capabilities: { experimentalApi: true },
235
+ clientInfo: { name: "bazis", title: "Bazis", version: "0.98.21" }, capabilities: { experimentalApi: true },
236
236
  }, 15_000, signal);
237
237
  if (resolve(text(initialized.codexHome, 4096)) !== this.paths.home) throw new CodexError("PROTOCOL_ERROR");
238
238
  client.notify("initialized");
@@ -50,7 +50,7 @@ function validateOrmHostedPlan(services: readonly HostedService[]): void {
50
50
  const owner = (service as { __bazisSchemaOwner?: { context: string; mode: string } }).__bazisSchemaOwner;
51
51
  return owner ? `${owner.context} uses ${owner.mode}` : "a module uses migrateOnStart or migrations";
52
52
  };
53
- throw new SchemaAdmissionError("ORM_SCHEMA_HOSTED_PHASE_CONFLICT", `Schema admission and legacy ORM schema authority cannot be composed together: ${[...strict, ...legacy].map(describe).join(", ")}. Use one schema mode in the application: ensureCreated in every module, or migrateOnStart/migrations in every module.`);
53
+ throw new SchemaAdmissionError("ORM_SCHEMA_HOSTED_PHASE_CONFLICT", `Schema admission and legacy ORM schema authority cannot be composed together: ${[...strict, ...legacy].map(describe).join(", ")}. Use one schema mode in the application: ensureCreated (with or without migrations) in every module, or migrateOnStart/migrations without ensureCreated in every module.`);
54
54
  }
55
55
  for (const service of services) {
56
56
  const framework = isOrmProviderLifecycle(service)
@@ -1,6 +1,6 @@
1
1
  import { ormHostedPlanValidator } from "./OrmHostedPlan.validator";
2
2
  import type { HostedService } from "../di";
3
- import { DatabaseFacade, type DbContextOptions, type Migration } from "../../library/orm";
3
+ import { DatabaseFacade, type DbContextOptions, type EnsureCreatedWithMigrationsResult, type Migration } from "../../library/orm";
4
4
  import { compileExpectedSchema } from "../../library/orm/Schema/ExpectedSchema";
5
5
 
6
6
  /**
@@ -29,6 +29,8 @@ export class OrmLifecycle implements HostedService {
29
29
  };
30
30
  /** Internal hosted-plan marker: the context and its startup schema mode, for readable plan errors. */
31
31
  readonly __bazisSchemaOwner: { readonly context: string; readonly mode: string };
32
+ /** `ensureCreated` owns the versioned migrations of this context (run or baselined before the check). */
33
+ private readonly withMigrations: boolean;
32
34
  private connectionClosed = false;
33
35
  private closePromise?: Promise<void>;
34
36
 
@@ -48,6 +50,7 @@ export class OrmLifecycle implements HostedService {
48
50
  contextName = "DbContext",
49
51
  ) {
50
52
  const modes = [ensureCreated && "ensureCreated", migrateOnStart && "migrateOnStart", runMigrationsOnStart && migrations.length > 0 && "migrations"].filter(Boolean);
53
+ this.withMigrations = ensureCreated && runMigrationsOnStart && migrations.length > 0;
51
54
  this.__bazisSchemaOwner = Object.freeze({ context: contextName, mode: modes.join(" + ") || "none" });
52
55
  this.phase = ensureCreated && options.provider.name === "postgres" ? -105 : -100;
53
56
  this.__bazisLegacySchemaAuthority = this.phase === -100 && (ensureCreated || migrateOnStart || (runMigrationsOnStart && migrations.length > 0));
@@ -72,10 +75,17 @@ export class OrmLifecycle implements HostedService {
72
75
  const database = new DatabaseFacade(this.options.provider, this.options.model);
73
76
  try {
74
77
  if (this.ensureCreated) {
75
- const result = await database.ensureCreated();
78
+ const result: Partial<EnsureCreatedWithMigrationsResult> & Pick<EnsureCreatedWithMigrationsResult, "warnings"> = this.withMigrations ? await database.ensureCreatedWithMigrations(this.migrations) : await database.ensureCreated();
79
+ // Logged in execution order: migrations, schema changes, then the baseline record.
80
+ if (result.migrated && result.migrated.length > 0) {
81
+ console.info(`[orm:migrations] applied: ${result.migrated.join(", ")}`);
82
+ }
76
83
  if (result.applied && result.applied.length > 0) {
77
84
  console.info(`[orm:schema] applied ${result.applied.length} operation(s): ${result.applied.join(", ")}`);
78
85
  }
86
+ if (result.baselined && result.baselined.length > 0) {
87
+ console.info(`[orm:migrations] baseline: the schema was created from the model, recorded as applied without running: ${result.baselined.join(", ")}`);
88
+ }
79
89
  for (const warning of result.warnings) {
80
90
  console.warn(`[orm:schema] ${warning}`);
81
91
  }
@@ -89,7 +99,7 @@ export class OrmLifecycle implements HostedService {
89
99
  console.warn(`[orm:migrate] ${warning}`);
90
100
  }
91
101
  }
92
- if (this.runMigrationsOnStart && this.migrations.length > 0) {
102
+ if (this.runMigrationsOnStart && this.migrations.length > 0 && !this.withMigrations) {
93
103
  const result = await database.migrateVersioned(this.migrations);
94
104
  if (result.applied.length > 0) {
95
105
  console.info(`[orm:migrations] applied: ${result.applied.join(", ")}`);
@@ -121,7 +121,7 @@ export function ormModule<TContext extends DbContext>(config: OrmModuleConfig<TC
121
121
  attachOwnedStoreRegistration(module, buildConfig.context, buildConfig.entities ?? [], config.ownedStore);
122
122
  return module;
123
123
  }
124
- if (config.ensureCreated && (config.migrateOnStart || config.runMigrationsOnStart || (config.migrations?.length ?? 0) > 0)) throw new OrmError("ensureCreated is mutually exclusive with ORM migration startup options.");
124
+ if (config.ensureCreated && config.migrateOnStart) throw new OrmError("ensureCreated and migrateOnStart are mutually exclusive: ensureCreated already adds the safe changes. Put other changes into migrations with runMigrationsOnStart: true.");
125
125
  if (config.ensureCreated && config.provider?.name === "postgres" && config.context) throw new OrmError("PostgreSQL ensureCreated requires the shared DATABASE_PROVIDER from @Infra.");
126
126
  // "Connection" mode: a provider only, no context.
127
127
  if (!config.context) {
@@ -5,6 +5,15 @@ import { Migrator, type MigrationResult } from "./Schema/Migrator";
5
5
  import { MigrationRunner, type Migration, type VersionedMigrationResult } from "./Schema/MigrationRunner";
6
6
  import { SchemaDiffer } from "./Schema/SchemaDiffer";
7
7
  import { SchemaAdmissionEngine, type EnsureCreatedResult } from "./Schema/SchemaAdmission";
8
+ import { entityStorageKey } from "./Schema/tableKey";
9
+
10
+ /** Result of `ensureCreated` together with versioned migrations. */
11
+ export interface EnsureCreatedWithMigrationsResult extends EnsureCreatedResult {
12
+ /** Migrations run before the schema check. */
13
+ readonly migrated: readonly string[];
14
+ /** Migrations recorded as applied without running, because the schema was created from the model. */
15
+ readonly baselined: readonly string[];
16
+ }
8
17
  import { SchemaAdmissionError } from "./errors";
9
18
  import { physicalColumnTypes } from "./Schema/physicalColumnTypes";
10
19
  import { bindResolvedForeignKey } from "./Providers/resolvedForeignKey";
@@ -47,6 +56,32 @@ export class DatabaseFacade {
47
56
  return { warnings: [] };
48
57
  }
49
58
 
59
+ /**
60
+ * `ensureCreated` with versioned migrations, under the migration lock so that
61
+ * starting instances do not race:
62
+ *
63
+ * - none of the context tables exist yet: `ensureCreated` creates the current
64
+ * model and the migrations are recorded as applied without running (a
65
+ * baseline: the model already contains their result, so a seed `INSERT` in
66
+ * a migration is skipped here too);
67
+ * - otherwise pending migrations run first (`ALTER`, renames, data moves),
68
+ * then `ensureCreated` adds what is still missing and verifies the result.
69
+ */
70
+ async ensureCreatedWithMigrations(migrations: readonly Migration[]): Promise<EnsureCreatedWithMigrationsResult> {
71
+ const work = async (): Promise<EnsureCreatedWithMigrationsResult> => {
72
+ const runner = new MigrationRunner(this.provider, migrations);
73
+ const existing = await this.provider.introspect();
74
+ const fresh = this.models.entities.every((model) => !existing.tables.has(entityStorageKey(model)) && !existing.tables.has(model.tableName));
75
+ if (fresh) {
76
+ const created = await this.ensureCreated();
77
+ return { ...created, migrated: [], baselined: await runner.baseline() };
78
+ }
79
+ const { applied } = await runner.migrate();
80
+ return { ...(await this.ensureCreated()), migrated: applied, baselined: [] };
81
+ };
82
+ return this.provider.withMigrationLock ? this.provider.withMigrationLock(work) : work();
83
+ }
84
+
50
85
  /**
51
86
  * Additive auto-migration of the schema for all context entities (enabled in
52
87
  * the module: `ormBazis: { migrateOnStart: true }`): introspects the database,
@@ -61,6 +61,27 @@ export class MigrationRunner {
61
61
  return { applied, rolledBack: [] };
62
62
  }
63
63
 
64
+ /**
65
+ * Records pending migrations as applied without running them. Used when the
66
+ * schema was just created from the current model, which already contains
67
+ * their result.
68
+ */
69
+ async baseline(): Promise<readonly string[]> {
70
+ return this.withMigrationLock(async () => {
71
+ await this.ensureHistory();
72
+ const appliedSet = await this.loadApplied();
73
+ const recorded: string[] = [];
74
+ for (const migration of this.migrations.filter((item) => !appliedSet.has(item.id))) {
75
+ await this.provider.execute(
76
+ `INSERT INTO ${this.quote(HISTORY_TABLE)} (${this.quote("MigrationId")}, ${this.quote("AppliedAt")}) VALUES (${this.param(0)}, ${this.param(1)})`,
77
+ [migration.id, new Date().toISOString()],
78
+ );
79
+ recorded.push(migration.id);
80
+ }
81
+ return recorded;
82
+ });
83
+ }
84
+
64
85
  /** Rolls back the last `steps` migrations (requires `down`). */
65
86
  async rollback(steps = 1): Promise<VersionedMigrationResult> {
66
87
  if (!Number.isSafeInteger(steps) || steps < 0) {
@@ -33,7 +33,7 @@ export class SchemaMigrationRequiredError extends SchemaAdmissionError {
33
33
 
34
34
  function schemaVerificationMessage(summary: string, verification: SchemaVerificationResult): string {
35
35
  return [summary, formatSchemaDifferences(verification),
36
- "Check the application version and target database. Align the ORM model and database schema; apply an explicit migration if a database change is intended.",
36
+ "Check the application version and target database. Align the ORM model and database schema; apply an explicit migration if a database change is intended (with ensureCreated: add it to the module's migrations with runMigrationsOnStart: true).",
37
37
  ].filter(Boolean).join("\n");
38
38
  }
39
39
 
@@ -132,6 +132,7 @@ export type {
132
132
  } from "./Schema/introspection";
133
133
  export type { SchemaDifferenceCode, SafeSchemaDescriptor, SchemaDifference, SchemaVerificationResult } from "./Schema/ExactSchemaVerifier";
134
134
  export type { EnsureCreatedResult } from "./Schema/SchemaAdmission";
135
+ export type { EnsureCreatedWithMigrationsResult } from "./DatabaseFacade";
135
136
  export { SchemaAdmissionError, SchemaMigrationRequiredError, SchemaVerificationError } from "./errors";
136
137
  export type { SchemaAdmissionErrorCode } from "./errors";
137
138
  export { compileCheck, renderCheck } from "./Schema/CheckExpression";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bazis",
3
- "version": "0.98.20",
3
+ "version": "0.98.21",
4
4
  "description": "Modular backend framework for Bun in TypeScript: DI wired by codegen, HTTP, a PostgreSQL ORM, JWT, WebSocket, agents and a CLI.",
5
5
  "license": "MIT",
6
6
  "author": "Alexander Alenin",