@happyvertical/smrt-core 0.42.7 → 0.43.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.
Files changed (101) hide show
  1. package/AGENTS.md +35 -2
  2. package/agents/schema-paths.md +37 -15
  3. package/dist/cascade.d.ts +7 -6
  4. package/dist/cascade.d.ts.map +1 -1
  5. package/dist/cascade.js +19 -21
  6. package/dist/cascade.js.map +1 -1
  7. package/dist/class.d.ts +10 -0
  8. package/dist/class.d.ts.map +1 -1
  9. package/dist/class.js +21 -0
  10. package/dist/class.js.map +1 -1
  11. package/dist/decorators/index.d.ts +50 -15
  12. package/dist/decorators/index.d.ts.map +1 -1
  13. package/dist/decorators/index.js +23 -11
  14. package/dist/decorators/index.js.map +1 -1
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2 -1
  18. package/dist/manifest/static-manifest.d.ts.map +1 -1
  19. package/dist/manifest/static-manifest.js +17 -1
  20. package/dist/manifest/static-manifest.js.map +1 -1
  21. package/dist/manifest/store.js +1 -1
  22. package/dist/manifest/store.js.map +1 -1
  23. package/dist/manifest.json +20 -1
  24. package/dist/migrations/differ.d.ts +2 -0
  25. package/dist/migrations/differ.d.ts.map +1 -1
  26. package/dist/migrations/differ.js +103 -0
  27. package/dist/migrations/differ.js.map +1 -1
  28. package/dist/migrations/generator.d.ts.map +1 -1
  29. package/dist/migrations/generator.js +26 -2
  30. package/dist/migrations/generator.js.map +1 -1
  31. package/dist/migrations/orchestrate.d.ts.map +1 -1
  32. package/dist/migrations/orchestrate.js +4 -1
  33. package/dist/migrations/orchestrate.js.map +1 -1
  34. package/dist/object.d.ts +4 -4
  35. package/dist/object.js +4 -4
  36. package/dist/object.js.map +1 -1
  37. package/dist/registry/schema-builder.d.ts +6 -0
  38. package/dist/registry/schema-builder.d.ts.map +1 -1
  39. package/dist/registry/schema-builder.js +80 -8
  40. package/dist/registry/schema-builder.js.map +1 -1
  41. package/dist/registry.d.ts +5 -7
  42. package/dist/registry.d.ts.map +1 -1
  43. package/dist/registry.js +6 -8
  44. package/dist/registry.js.map +1 -1
  45. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  46. package/dist/scanner/manifest-generator.js +64 -18
  47. package/dist/scanner/manifest-generator.js.map +1 -1
  48. package/dist/scanner/types.d.ts +7 -1
  49. package/dist/scanner/types.d.ts.map +1 -1
  50. package/dist/scanner/types.js.map +1 -1
  51. package/dist/schema/ddl/base-strategy.d.ts.map +1 -1
  52. package/dist/schema/ddl/base-strategy.js +2 -0
  53. package/dist/schema/ddl/base-strategy.js.map +1 -1
  54. package/dist/schema/ddl/duckdb-strategy.d.ts +1 -0
  55. package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
  56. package/dist/schema/ddl/duckdb-strategy.js +23 -1
  57. package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
  58. package/dist/schema/ddl/postgres-strategy.js +1 -1
  59. package/dist/schema/foreign-key-ddl.d.ts +16 -0
  60. package/dist/schema/foreign-key-ddl.d.ts.map +1 -0
  61. package/dist/schema/foreign-key-ddl.js +85 -0
  62. package/dist/schema/foreign-key-ddl.js.map +1 -0
  63. package/dist/schema/foreign-key-planner.d.ts +18 -0
  64. package/dist/schema/foreign-key-planner.d.ts.map +1 -0
  65. package/dist/schema/foreign-key-planner.js +109 -0
  66. package/dist/schema/foreign-key-planner.js.map +1 -0
  67. package/dist/schema/foreign-key-policy.d.ts +21 -0
  68. package/dist/schema/foreign-key-policy.d.ts.map +1 -0
  69. package/dist/schema/foreign-key-policy.js +41 -0
  70. package/dist/schema/foreign-key-policy.js.map +1 -0
  71. package/dist/schema/generator.d.ts +3 -0
  72. package/dist/schema/generator.d.ts.map +1 -1
  73. package/dist/schema/generator.js +65 -13
  74. package/dist/schema/generator.js.map +1 -1
  75. package/dist/schema/index.d.ts +3 -0
  76. package/dist/schema/index.d.ts.map +1 -1
  77. package/dist/schema/index.js +4 -1
  78. package/dist/schema/manifest-schema.d.ts.map +1 -1
  79. package/dist/schema/manifest-schema.js +21 -3
  80. package/dist/schema/manifest-schema.js.map +1 -1
  81. package/dist/schema/schema-aggregator.d.ts +7 -1
  82. package/dist/schema/schema-aggregator.d.ts.map +1 -1
  83. package/dist/schema/schema-aggregator.js +54 -9
  84. package/dist/schema/schema-aggregator.js.map +1 -1
  85. package/dist/schema/schema-manager.d.ts +1 -6
  86. package/dist/schema/schema-manager.d.ts.map +1 -1
  87. package/dist/schema/schema-manager.js +26 -30
  88. package/dist/schema/schema-manager.js.map +1 -1
  89. package/dist/schema/types.d.ts +12 -5
  90. package/dist/schema/types.d.ts.map +1 -1
  91. package/dist/schema/utils.d.ts +1 -1
  92. package/dist/schema/utils.d.ts.map +1 -1
  93. package/dist/schema/utils.js +15 -1
  94. package/dist/schema/utils.js.map +1 -1
  95. package/dist/schema.js +4 -1
  96. package/dist/smrt-knowledge.json +18 -8
  97. package/dist/testing/database.d.ts +11 -1
  98. package/dist/testing/database.d.ts.map +1 -1
  99. package/dist/testing/database.js +80 -9
  100. package/dist/testing/database.js.map +1 -1
  101. package/package.json +4 -4
@@ -115,6 +115,12 @@ export interface FieldsToColumnsOptions {
115
115
  * Declared defaults are still emitted.
116
116
  */
117
117
  stiUnionColumns?: boolean;
118
+ /**
119
+ * Physical column names that form the table's natural conflict key.
120
+ * Undeclared delete actions on foreign-key members use the shared CASCADE
121
+ * default, matching app-side relationship cleanup.
122
+ */
123
+ conflictColumns?: readonly string[];
118
124
  }
119
125
  /**
120
126
  * Convert a Map of field definitions to column definitions
@@ -1 +1 @@
1
- {"version":3,"file":"schema-builder.d.ts","sourceRoot":"","sources":["../../src/registry/schema-builder.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAG3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAM7D,OAAO,KAAK,EACV,gBAAgB,EAEhB,gB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AAE,gBAAgB,CAAC,EACzC,KAAK,UAAQ,EACb,MAAM,CAAC,EAAE,cAAc,GACtB,MAAM,CA2DR;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;OAQG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;OAIG;IACH,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACrC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,EACpC,OAAO,CAAC,EAAE,sBAAsB,GAC/B,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAkHlC;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC,GACjC,WAAW,CAqBb"}
@@ -1,6 +1,8 @@
1
+ import { requireForeignKeyAction, resolveForeignKeyDeleteAction } from "../schema/foreign-key-policy.js";
1
2
  import { classnameToTablename, toSnakeCase } from "../utils/naming.js";
2
3
  import { formatDefaultValue as formatDefaultValue$1, quoteIdentifier } from "../schema/sql-identifiers.js";
3
4
  import { shortenIdentifier } from "../schema/index-utils.js";
5
+ import { renderForeignKeyConstraint, schemaForeignKeys } from "../schema/foreign-key-ddl.js";
4
6
  import { getDDLStrategy } from "../schema/ddl/index.js";
5
7
  import { getClasses, getCollectionTableNames } from "./shared-state.js";
6
8
  import { findClass } from "./name-resolver.js";
@@ -189,6 +191,54 @@ function withConflictIndex(tableName, columns, indexes, conflictColumns) {
189
191
  if (indexes.some((index) => index.name === name)) return indexes.map((index) => index.name === name ? conflictIndex : index);
190
192
  return [...indexes, conflictIndex];
191
193
  }
194
+ function applyContributorForeignKeys(tableSchema, contributor) {
195
+ const conflictColumns = new Set(tableSchema.conflictColumns);
196
+ for (const [fieldName, field] of contributor.registered.fields) {
197
+ if (field.type !== "foreignKey" || !field.related) continue;
198
+ const columnName = toSnakeCase(fieldName);
199
+ const column = tableSchema.columns[columnName];
200
+ if (!column) continue;
201
+ if (field._meta?.__tenancy?.isTenantIdField === true || field.__tenancy?.isTenantIdField === true) {
202
+ column.foreignKey = void 0;
203
+ continue;
204
+ }
205
+ const [targetName, declaredTargetColumn] = field.related.split(".");
206
+ const targetBase = ObjectRegistry.getSTIBase(targetName) || targetName;
207
+ const registeredTarget = ObjectRegistry.getClass(targetBase);
208
+ const targetColumn = declaredTargetColumn || Array.from(ObjectRegistry.getFields(targetBase).entries()).find(([, targetField]) => targetField._meta?.primaryKey === true)?.[0] || "id";
209
+ if (registeredTarget && !field._meta?.sqlType) {
210
+ const targetColumnName = toSnakeCase(targetColumn);
211
+ const targetColumnType = registeredTarget.schema?.columns?.[targetColumnName]?.type || (targetColumnName === "id" ? registeredTarget.config.idType === "text" ? "TEXT" : "UUID" : void 0);
212
+ if (targetColumnType) column.type = targetColumnType;
213
+ }
214
+ if (field._meta?.constraint === false) {
215
+ column.foreignKey = void 0;
216
+ continue;
217
+ }
218
+ const manifestForeignKey = contributor.registered.schema?.columns?.[columnName]?.foreignKey;
219
+ if (manifestForeignKey) {
220
+ column.foreignKey = manifestForeignKey;
221
+ continue;
222
+ }
223
+ if (!registeredTarget) {
224
+ column.foreignKey = void 0;
225
+ continue;
226
+ }
227
+ const targetTable = ObjectRegistry.getTableName(targetBase) || classnameToTablename(targetBase);
228
+ const { action } = resolveForeignKeyDeleteAction({
229
+ declared: field._meta?.onDelete,
230
+ isConflictColumn: conflictColumns.has(columnName),
231
+ isTenantIdField: false
232
+ });
233
+ column.foreignKey = {
234
+ table: targetTable,
235
+ column: toSnakeCase(targetColumn),
236
+ onDelete: action,
237
+ onUpdate: "CASCADE",
238
+ ...typeof field._meta?.constraint === "object" ? { engines: [...field._meta.constraint.engines] } : {}
239
+ };
240
+ }
241
+ }
192
242
  /**
193
243
  * Resolve the physical table a registered class writes to.
194
244
  *
@@ -292,7 +342,11 @@ function buildMergedTableSchemas() {
292
342
  const tableSchemas = {};
293
343
  for (const [tableName, contributors] of contributorsByTable) for (const contributor of sortTableContributors(contributors)) {
294
344
  const { registered, simpleName, isSTI } = contributor;
295
- const columnsToUse = mergeRuntimeFieldColumns(simpleName, registered.schema?.columns, registered.fields, { stiUnionColumns: isSTI });
345
+ const conflictColumns = ObjectRegistry.getConflictColumns(contributor.conflictKey);
346
+ const columnsToUse = mergeRuntimeFieldColumns(simpleName, registered.schema?.columns, registered.fields, {
347
+ stiUnionColumns: isSTI,
348
+ conflictColumns
349
+ });
296
350
  let tableSchema = tableSchemas[tableName];
297
351
  if (!tableSchema) {
298
352
  tableSchema = {
@@ -304,10 +358,11 @@ function buildMergedTableSchemas() {
304
358
  indexes: [],
305
359
  ddl: registered.schema?.ddl || "",
306
360
  isSTI,
307
- conflictColumns: ObjectRegistry.getConflictColumns(contributor.conflictKey)
361
+ conflictColumns
308
362
  };
309
363
  tableSchemas[tableName] = tableSchema;
310
364
  } else for (const [colName, colDef] of Object.entries(columnsToUse)) if (!tableSchema.columns[colName]) tableSchema.columns[colName] = colDef;
365
+ applyContributorForeignKeys(tableSchema, contributor);
311
366
  const schemaIndexes = registered.schema?.indexes;
312
367
  if (schemaIndexes && schemaIndexes.length > 0) {
313
368
  const existingNames = new Set(tableSchema.indexes.map((index) => index.name));
@@ -352,6 +407,8 @@ function getAllSchemas(engine) {
352
407
  version: "",
353
408
  dependencies: []
354
409
  };
410
+ mergedSchema.foreignKeys = schemaForeignKeys(mergedSchema);
411
+ mergedSchema.dependencies = mergedSchema.foreignKeys.map((foreignKey) => foreignKey.referencesTable).filter((dependency) => dependency !== tableName);
355
412
  let ddl;
356
413
  if (Object.keys(tableSchema.columns).length === 0 && tableSchema.ddl) {
357
414
  if (engine) throw new Error(`Cannot materialize schema '${tableName}' for ${engine}: the manifest has no structured columns`);
@@ -389,15 +446,20 @@ function getAllSchemasAsDefinitions() {
389
446
  const schemas = {};
390
447
  for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {
391
448
  if (Object.keys(tableSchema.columns).length === 0) continue;
449
+ const ddl = generateDDLFromColumns(tableName, tableSchema.columns, tableSchema.isSTI);
450
+ const foreignKeys = schemaForeignKeys({
451
+ columns: tableSchema.columns,
452
+ foreignKeys: []
453
+ });
392
454
  schemas[tableName] = {
393
455
  tableName,
394
- ddl: generateDDLFromColumns(tableName, tableSchema.columns, tableSchema.isSTI),
456
+ ddl,
395
457
  columns: tableSchema.columns,
396
458
  indexes: withConflictIndex(tableName, tableSchema.columns, tableSchema.indexes, tableSchema.conflictColumns),
397
459
  triggers: [],
398
- foreignKeys: [],
460
+ foreignKeys,
399
461
  version: "",
400
- dependencies: []
462
+ dependencies: foreignKeys.map((foreignKey) => foreignKey.referencesTable).filter((dependency) => dependency !== tableName)
401
463
  };
402
464
  }
403
465
  return schemas;
@@ -429,6 +491,10 @@ function generateDDLFromColumns(tableName, columns, isSTI = false, engine) {
429
491
  }
430
492
  columnLines.push(parts.join(" "));
431
493
  }
494
+ for (const foreignKey of schemaForeignKeys({
495
+ columns,
496
+ foreignKeys: []
497
+ })) columnLines.push(` ${renderForeignKeyConstraint(tableName, foreignKey)}`);
432
498
  sql += columnLines.join(",\n");
433
499
  if (columns.slug && columns.context) if (isSTI && columns._meta_type) sql += ",\n UNIQUE(slug, context, _meta_type)";
434
500
  else sql += ",\n UNIQUE(slug, context)";
@@ -469,6 +535,7 @@ function formatDefaultValue(value, type) {
469
535
  */
470
536
  function fieldsToColumns(fields, options) {
471
537
  const columns = {};
538
+ const conflictColumns = new Set((options?.conflictColumns ?? []).map((column) => toSnakeCase(column)));
472
539
  for (const [fieldName, fieldDef] of fields) {
473
540
  if (fieldName === "id" || fieldName === "created_at" || fieldName === "updated_at" || fieldName === "slug" || fieldName === "context") continue;
474
541
  if (fieldDef.transient || fieldDef._meta?.transient) continue;
@@ -488,14 +555,19 @@ function fieldsToColumns(fields, options) {
488
555
  description
489
556
  };
490
557
  if (defaultValue !== void 0 && shouldEmitDefault(fieldDef, normalizedSqlType, defaultValue)) column.defaultValue = defaultValue;
491
- if (fieldDef.type === "foreignKey" && fieldDef.related) {
558
+ if (fieldDef.type === "foreignKey" && fieldDef.related && fieldDef._meta?.constraint !== false && fieldDef._meta?.__tenancy?.isTenantIdField !== true && !fieldDef.__tenancy?.isTenantIdField) {
492
559
  const [table, columnName = "id"] = fieldDef.related.split(".");
493
560
  const fieldMeta = fieldDef._meta;
494
561
  column.foreignKey = {
495
562
  table: classnameToTablename(table),
496
563
  column: columnName,
497
- onDelete: fieldMeta?.onDelete ?? "CASCADE",
498
- onUpdate: fieldMeta?.onUpdate ?? "CASCADE"
564
+ onDelete: resolveForeignKeyDeleteAction({
565
+ declared: fieldMeta?.onDelete,
566
+ isConflictColumn: conflictColumns.has(toSnakeCase(fieldName)),
567
+ isTenantIdField: false
568
+ }).action,
569
+ onUpdate: fieldMeta?.onUpdate === void 0 ? "CASCADE" : requireForeignKeyAction(fieldMeta.onUpdate, `${fieldName} ON UPDATE`),
570
+ ...typeof fieldDef._meta?.constraint === "object" ? { engines: [...fieldDef._meta.constraint.engines] } : {}
499
571
  };
500
572
  }
501
573
  columns[toSnakeCase(fieldName)] = column;
@@ -1 +1 @@
1
- {"version":3,"file":"schema-builder.js","names":[],"sources":["../../src/registry/schema-builder.ts"],"sourcesContent":["/**\n * Schema building logic for the SMRT ObjectRegistry.\n *\n * Extracted from registry.ts as part of issue #1006.\n */\n\nimport { ObjectRegistry } from '../registry';\nimport type { FieldDefinition } from '../scanner/types.js';\nimport { conflictIndexName } from '../schema/conflict-target.js';\nimport { getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport { shortenIdentifier } from '../schema/index-utils.js';\nimport {\n formatDefaultValue as formatDefaultValueShared,\n quoteIdentifier,\n} from '../schema/sql-identifiers.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaDefinition,\n SQLDataType,\n} from '../schema/types.js';\nimport { classnameToTablename, toSnakeCase } from '../utils';\nimport {\n type CollectionRegistrationLookup,\n isCollectionRegistration,\n} from './collection-resolution';\nimport { readFieldAttribute } from './manifest-field-merge';\nimport { findClass } from './name-resolver';\nimport { getClasses, getCollectionTableNames } from './shared-state';\nimport type { RegisteredClass } from './types';\n\ntype ForeignKeyAction = NonNullable<\n NonNullable<ColumnDefinition['foreignKey']>['onDelete']\n>;\n\nconst collectionRegistrationLookup: CollectionRegistrationLookup = {\n findClass,\n findClassInPackage: (packageName, className) =>\n ObjectRegistry.getClassInPackage(packageName, className),\n getInheritanceChain: (className) =>\n ObjectRegistry.getInheritanceChain(className),\n};\n\nfunction applyDecoratorSqlTypeOverrides(\n className: string,\n columns: Record<string, ColumnDefinition>,\n): Record<string, ColumnDefinition> {\n const decorators = ObjectRegistry.getFieldDecorators(className);\n if (!decorators.size) {\n return columns;\n }\n\n for (const [fieldName, options] of decorators) {\n if (!options?.sqlType) {\n continue;\n }\n\n const columnName = toSnakeCase(fieldName);\n const existing = columns[columnName];\n if (!existing) {\n continue;\n }\n\n const referenceKind = getReferenceKind(options as FieldDefinition);\n columns[columnName] = {\n ...existing,\n type: String(options.sqlType).toUpperCase() as SQLDataType,\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n\n return columns;\n}\n\nfunction mergeRuntimeFieldColumns(\n className: string,\n schemaColumns: Record<string, ColumnDefinition> | undefined,\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columnsToUse = { ...(schemaColumns || {}) };\n\n if (fields.size > 0) {\n const fieldColumns = fieldsToColumns(fields, options);\n for (const [columnName, columnDef] of Object.entries(fieldColumns)) {\n if (!columnsToUse[columnName]) {\n columnsToUse[columnName] = columnDef;\n }\n }\n\n for (const [fieldName, fieldDef] of fields) {\n const columnName = toSnakeCase(fieldName);\n const existing = columnsToUse[columnName];\n if (!existing) {\n continue;\n }\n\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef as unknown as { sqlType?: string }).sqlType;\n const referenceKind = getReferenceKind(fieldDef);\n columnsToUse[columnName] = {\n ...existing,\n ...(sqlType\n ? { type: String(sqlType).toUpperCase() as SQLDataType }\n : {}),\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n }\n\n applyDecoratorSqlTypeOverrides(className, columnsToUse);\n return columnsToUse;\n}\n\nfunction getReferenceKind(\n fieldDef: FieldDefinition,\n): ColumnDefinition['referenceKind'] | undefined {\n if (\n (\n fieldDef as unknown as {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField ||\n fieldDef._meta?.__tenancy?.isTenantIdField\n ) {\n return 'tenantId';\n }\n\n if (fieldDef.type === 'foreignKey') {\n return 'foreignKey';\n }\n\n if (fieldDef.type === 'crossPackageRef') {\n return 'crossPackageRef';\n }\n\n return undefined;\n}\n\nfunction shouldEmitDefault(\n fieldDef: FieldDefinition,\n sqlType: SQLDataType,\n defaultValue: unknown,\n) {\n return !(\n getReferenceKind(fieldDef) === 'tenantId' &&\n sqlType === 'UUID' &&\n defaultValue === ''\n );\n}\n\n/**\n * Fallback base columns for a table whose contributing class carries no\n * manifest columns.\n *\n * These mirror what the manifest schema generators emit for the same table\n * (`generateSchemaFromManifest` / `generateSTISchemaFromManifest`), so a table\n * assembled from runtime field metadata alone has the same NOT NULL and\n * DEFAULT shape as one assembled from a manifest. Divergence here is what made\n * the merged table shape depend on which class registered first (#2372).\n */\nfunction createBaseColumns(\n registered: {\n config?: { idType?: 'uuid' | 'text' };\n },\n isSTI: boolean,\n): Record<string, ColumnDefinition> {\n const baseColumns: Record<string, ColumnDefinition> = {\n id: {\n type: registered.config?.idType === 'text' ? 'TEXT' : 'UUID',\n primaryKey: true,\n notNull: true,\n referenceKind: 'id',\n },\n slug: { type: 'TEXT', notNull: true },\n context: { type: 'TEXT', notNull: true, defaultValue: '' },\n created_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n updated_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n };\n\n // STI tables also carry the discriminator and the meta payload column\n // (issue #690: db:diff needs them to detect schema changes).\n if (isSTI) {\n baseColumns._meta_type = { type: 'TEXT', notNull: true };\n baseColumns._meta_data = { type: 'JSON', notNull: false };\n }\n\n return baseColumns;\n}\n\n/**\n * Get cached schema definition for a registered class\n *\n * @param name - Name of the registered class\n * @returns Schema definition or undefined if not found\n * @example\n * ```typescript\n * const schema = getSchema('Product');\n * console.log(schema.tableName); // 'products'\n * console.log(schema.ddl); // 'CREATE TABLE...'\n * ```\n */\nexport function getSchema(name: string): SchemaDefinition | undefined {\n // Issue #951: Use findClass for multi-strategy lookup\n const registered = findClass(name);\n return registered?.schema;\n}\n\n/**\n * Get SQL DDL statement for a registered class\n *\n * @param name - Name of the registered class\n * Cached manifest DDL contains abstract types and is not safe to execute on\n * PostgreSQL. New executable paths must pass a target engine. Omitting it is\n * retained for backward compatibility with consumers that only inspect the\n * legacy engine-neutral manifest string.\n *\n * @param engine - Database engine that will execute the DDL\n * @returns Engine-specific SQL DDL, or the legacy cached DDL when omitted\n * @example\n * ```typescript\n * const ddl = ObjectRegistry.getSchemaDDL('Product', 'postgres');\n * await db.query(ddl);\n * ```\n */\nexport function getSchemaDDL(\n name: string,\n engine?: DatabaseEngine,\n): string | undefined {\n const schema = getSchema(name);\n if (!schema) return undefined;\n if (engine && Object.keys(schema.columns).length === 0) {\n throw new Error(\n `Cannot materialize schema '${name}' for ${engine}: the manifest has no structured columns`,\n );\n }\n return engine\n ? getDDLStrategy(engine).generateCreateTable(schema)\n : schema.ddl;\n}\n\n/**\n * Get table name for a registered class\n *\n * @param name - Name of the registered class\n * @returns Table name or undefined if not found\n * @example\n * ```typescript\n * const tableName = getTableName('Product');\n * console.log(tableName); // 'products'\n * ```\n */\nexport function getTableName(name: string): string | undefined {\n // Check if this is a collection class - collections have their own tableName mapping\n const collectionTableName = getCollectionTableNames().get(name);\n if (collectionTableName) {\n return collectionTableName;\n }\n\n // For STI classes, return the STI base class's table name.\n // R5-canon: `getSTIBase` returns the qualified name; resolve `name`\n // (which may be simple) to its registration's qualified form for the\n // comparison.\n const stiBase = ObjectRegistry.getSTIBase(name);\n const registered = ObjectRegistry.getClass(name);\n const qualifiedName = registered?.qualifiedName ?? registered?.name ?? name;\n if (stiBase && stiBase !== qualifiedName) {\n return getSchema(stiBase)?.tableName;\n }\n return getSchema(name)?.tableName;\n}\n\nfunction withConflictIndex(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n indexes: IndexDefinition[],\n conflictColumns: string[],\n): IndexDefinition[] {\n if (\n conflictColumns.length === 0 ||\n !conflictColumns.every((column) => columns[column])\n ) {\n return indexes;\n }\n\n // `ON CONFLICT (id)` binds to the primary-key constraint itself; a second\n // unique index over the primary key column set adds nothing (#2359, A5).\n // Kept in step with SchemaGenerator.conflictColumnsArePrimaryKey().\n const primaryKeyColumns = Object.entries(columns)\n .filter(([, column]) => column.primaryKey === true)\n .map(([name]) => name);\n if (\n primaryKeyColumns.length > 0 &&\n primaryKeyColumns.length === conflictColumns.length &&\n primaryKeyColumns.every((column) => conflictColumns.includes(column))\n ) {\n return indexes;\n }\n\n const hasConflictIndex = indexes.some(\n (index) =>\n index.unique === true &&\n !index.where &&\n !index.jsonPath &&\n index.columns.length === conflictColumns.length &&\n index.columns.every((column) => conflictColumns.includes(column)),\n );\n if (hasConflictIndex) return indexes;\n\n // Same stable naming as SchemaGenerator (`schema/conflict-target.ts`), so\n // a manifest built before the runtime learned the tenant-aware default\n // (#2360) has its stale `<table>_slug_context_idx` REPLACED in place here\n // — the differ then swaps the live index by name — instead of a second,\n // suffixed unique index being appended beside the old global one.\n const tenantColumn = Object.entries(columns).find(\n ([, column]) => column.referenceKind === 'tenantId',\n )?.[0];\n // The composed name can exceed PostgreSQL's 63-byte limit on a long table.\n // Shortening here (rather than inside conflictIndexName) keeps the generator\n // paths, which run enforceIdentifierLimits() over their whole index list,\n // and this migrate leg agreeing on the final name (#2374).\n const name = shortenIdentifier(\n conflictIndexName(tableName, conflictColumns, tenantColumn),\n );\n const conflictIndex: IndexDefinition = {\n name,\n columns: conflictColumns,\n unique: true,\n };\n if (indexes.some((index) => index.name === name)) {\n return indexes.map((index) =>\n index.name === name ? conflictIndex : index,\n );\n }\n return [...indexes, conflictIndex];\n}\n\n/**\n * A registered class that contributes columns to one physical table.\n *\n * For a single-table-inheritance hierarchy every class in the hierarchy is a\n * contributor to the same table.\n */\ninterface TableContributor {\n registered: RegisteredClass;\n simpleName: string;\n qualifiedName: string;\n isSTI: boolean;\n /** True when this class is the STI base that owns the table. */\n isSTIBase: boolean;\n /** Inheritance depth; ancestors sort before descendants. */\n depth: number;\n /** Conflict-column lookup key (the STI base for STI members). */\n conflictKey: string;\n}\n\n/**\n * A merged physical table assembled from every class that contributes to it.\n */\ninterface MergedTableSchema {\n tableName: string;\n columns: Record<string, ColumnDefinition>;\n indexes: IndexDefinition[];\n ddl: string;\n isSTI: boolean;\n conflictColumns: string[];\n}\n\n/**\n * Resolve the physical table a registered class writes to.\n *\n * STI subclasses are folded onto their base's table. Returns `undefined` when\n * the class has no table (for example an unresolvable manifest stub).\n *\n * R5-canon: STI lookups use the qualified key so a colliding simple name in\n * another package cannot yield the wrong table strategy or STI base and move\n * this class's columns under that other package's table.\n */\nfunction resolveContributorTable(\n registered: RegisteredClass,\n fallbackName: string,\n): { tableName: string; contributor: TableContributor } | undefined {\n const simpleName = registered.name || fallbackName;\n const qualifiedName = registered.qualifiedName ?? simpleName;\n\n // STI subclasses loaded from external manifests can arrive with a null\n // tableName; registerFromManifest() then derives one from the class name.\n // Adopt the STI base's tableName instead so the subclass lands on the\n // shared table (issue #703).\n if (!registered.schema?.tableName && registered.extends) {\n if (ObjectRegistry.getTableStrategy(qualifiedName) === 'sti') {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName && stiBaseName !== qualifiedName) {\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n if (!registered.schema) {\n registered.schema = {\n tableName: '',\n ddl: '',\n columns: {},\n indexes: [],\n triggers: [],\n foreignKeys: [],\n dependencies: [],\n version: '',\n };\n }\n registered.schema.tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n if (!registered.schema?.tableName) {\n return undefined;\n }\n\n let tableName = registered.schema.tableName;\n const tableStrategy = ObjectRegistry.getTableStrategy(qualifiedName);\n const isSTI = tableStrategy === 'sti';\n let isSTIBase = isSTI;\n let conflictKey = qualifiedName;\n\n if (isSTI) {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName) {\n conflictKey = stiBaseName;\n if (stiBaseName !== qualifiedName) {\n isSTIBase = false;\n // STI subclasses serialize to the base class's table even when they\n // carry a tableName of their own (issue #693).\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n return {\n tableName,\n contributor: {\n registered,\n simpleName,\n qualifiedName,\n isSTI,\n isSTIBase,\n depth: ObjectRegistry.getInheritanceChain(qualifiedName).length,\n conflictKey,\n },\n };\n}\n\n/**\n * Order the classes that share one table deterministically.\n *\n * The first contributor seeds the table: it supplies the base columns, the\n * `idType`, the conflict columns and the cached DDL, and its columns win every\n * merge conflict. Registration order must not decide that, or the same\n * hierarchy yields a different table shape depending on which class a manifest\n * happens to list first — child-first dropped NOT NULL and DEFAULT from the\n * base columns (#2372).\n *\n * Order: the STI base first, then ancestors before descendants, then by\n * qualified name so the result is a total order.\n */\nfunction sortTableContributors(contributors: TableContributor[]) {\n return [...contributors].sort((a, b) => {\n if (a.isSTIBase !== b.isSTIBase) {\n return a.isSTIBase ? -1 : 1;\n }\n if (a.depth !== b.depth) {\n return a.depth - b.depth;\n }\n return a.qualifiedName.localeCompare(b.qualifiedName);\n });\n}\n\n/**\n * Assemble every physical table from the classes that contribute to it.\n *\n * Shared by {@link getAllSchemas} and {@link getAllSchemasAsDefinitions} so\n * both produce the same merged shape. The result depends only on what is\n * registered, never on the order it was registered in.\n */\nfunction buildMergedTableSchemas(): Record<string, MergedTableSchema> {\n // Pass 1: group contributing classes by physical table.\n const contributorsByTable = new Map<string, TableContributor[]>();\n\n for (const [className, registered] of getClasses()) {\n // Collection classes have no table of their own; their schemas carry\n // collection properties (loaded, options, ...) rather than columns.\n if (\n isCollectionRegistration(\n className,\n registered,\n collectionRegistrationLookup,\n )\n ) {\n continue;\n }\n\n const resolved = resolveContributorTable(registered, className);\n if (!resolved) {\n continue;\n }\n\n const existing = contributorsByTable.get(resolved.tableName);\n if (existing) {\n existing.push(resolved.contributor);\n } else {\n contributorsByTable.set(resolved.tableName, [resolved.contributor]);\n }\n }\n\n // Pass 2: merge each table's contributors in deterministic order.\n const tableSchemas: Record<string, MergedTableSchema> = {};\n\n for (const [tableName, contributors] of contributorsByTable) {\n for (const contributor of sortTableContributors(contributors)) {\n const { registered, simpleName, isSTI } = contributor;\n\n // The manifest schema stays authoritative for the columns it defines.\n // Runtime field metadata backfills columns the manifest never had (for\n // example tenantScoped injections) and applies explicit sqlType\n // overrides, without erasing richer manifest metadata.\n const columnsToUse = mergeRuntimeFieldColumns(\n simpleName,\n registered.schema?.columns,\n registered.fields,\n { stiUnionColumns: isSTI },\n );\n\n let tableSchema = tableSchemas[tableName];\n if (!tableSchema) {\n tableSchema = {\n tableName,\n columns: {\n ...createBaseColumns(registered, isSTI),\n ...columnsToUse,\n },\n indexes: [],\n ddl: registered.schema?.ddl || '',\n isSTI,\n conflictColumns: ObjectRegistry.getConflictColumns(\n contributor.conflictKey,\n ),\n };\n tableSchemas[tableName] = tableSchema;\n } else {\n // Another class sharing this table (STI): add only columns the\n // seeding contributor did not already define.\n for (const [colName, colDef] of Object.entries(columnsToUse)) {\n if (!tableSchema.columns[colName]) {\n tableSchema.columns[colName] = colDef;\n }\n }\n }\n\n // Merge indexes, keeping the first definition of each name.\n const schemaIndexes = registered.schema?.indexes;\n if (schemaIndexes && schemaIndexes.length > 0) {\n const existingNames = new Set(\n tableSchema.indexes.map((index) => index.name),\n );\n for (const index of schemaIndexes) {\n // Legacy string-format indexes carry no columns and cannot be merged.\n if (typeof index === 'string') {\n continue;\n }\n if (!existingNames.has(index.name)) {\n tableSchema.indexes.push(index);\n existingNames.add(index.name);\n }\n }\n }\n }\n }\n\n return tableSchemas;\n}\n\n/**\n * Get all pre-generated schemas for explicit adapter bootstrap paths.\n *\n * Returns schemas in SDK SchemaProvider format for all registered classes.\n * Tooling and test helpers can pass these to `getDatabase()` when they want\n * to bootstrap schema before runtime. Core runtime no longer does this\n * implicitly.\n *\n * @returns Record of table names to schema definitions\n * @example\n * ```typescript\n * const schemas = ObjectRegistry.getAllSchemas('json');\n * const db = await getDatabase({ type: 'json', url: './data', schemas });\n * ```\n */\nexport function getAllSchemas(\n engine?: DatabaseEngine,\n): Record<string, { tableName: string; ddl: string; indexes?: string[] }> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to output format, regenerating DDL for merged schemas\n const schemas: Record<\n string,\n { tableName: string; ddl: string; indexes?: string[] }\n > = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n const engineIndexes = engine\n ? withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n )\n : tableSchema.indexes;\n const mergedSchema: SchemaDefinition = {\n tableName,\n ddl: tableSchema.ddl,\n columns: tableSchema.columns,\n indexes: engineIndexes,\n triggers: [],\n foreignKeys: [],\n version: '',\n dependencies: [],\n };\n\n // Generate DDL from merged columns (or use original DDL if columns are empty)\n let ddl: string;\n if (Object.keys(tableSchema.columns).length === 0 && tableSchema.ddl) {\n if (engine) {\n throw new Error(\n `Cannot materialize schema '${tableName}' for ${engine}: the manifest has no structured columns`,\n );\n }\n // Preserve legacy inspection of cached engine-neutral DDL. Executable\n // target-engine paths fail above rather than returning unsafe SQL.\n ddl = tableSchema.ddl;\n } else if (Object.keys(tableSchema.columns).length === 0) {\n // Skip schemas with no columns and no original DDL\n continue;\n } else if (engine) {\n // Target-engine materialization must route the complete structured\n // schema through its strategy. In particular, DuckDB/JSON require\n // UNIQUE constraints inline for ON CONFLICT, and every strategy owns\n // CHECK/default/index-expression rendering.\n ddl = getDDLStrategy(engine).generateCreateTable(mergedSchema);\n } else {\n ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n }\n\n // Convert index definitions to SQL strings for SDK compatibility\n let indexSQL: string[] | undefined;\n if (engineIndexes.length > 0) {\n indexSQL = engine\n ? getDDLStrategy(engine).generateIndexes(mergedSchema)\n : engineIndexes.map((idx) => {\n const indexType = idx.unique ? 'UNIQUE INDEX' : 'INDEX';\n const columnList = idx.columns\n .map((col) => quoteIdentifier(col))\n .join(', ');\n return `CREATE ${indexType} IF NOT EXISTS ${quoteIdentifier(\n idx.name,\n )} ON ${quoteIdentifier(tableName)} (${columnList});`;\n });\n }\n\n schemas[tableName] = {\n tableName,\n ddl,\n indexes: indexSQL,\n };\n }\n\n return schemas;\n}\n\n/**\n * Get all registered schemas as SchemaDefinition objects\n *\n * Similar to getAllSchemas(), but returns SchemaDefinition format suitable\n * for use with SchemaComparer (migrations/differ.ts).\n *\n * Key difference: Indexes are kept as IndexDefinition objects instead of\n * being converted to SQL strings.\n *\n * @returns Map of tableName to SchemaDefinition\n */\nexport function getAllSchemasAsDefinitions(): Record<string, SchemaDefinition> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to SchemaDefinition format\n const schemas: Record<string, SchemaDefinition> = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n if (Object.keys(tableSchema.columns).length === 0) {\n continue;\n }\n\n // Generate DDL from columns\n const ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n\n schemas[tableName] = {\n tableName,\n ddl,\n columns: tableSchema.columns,\n indexes: withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n ),\n triggers: [],\n foreignKeys: [],\n version: '',\n dependencies: [],\n };\n }\n\n return schemas;\n}\n\n/**\n * Generate DDL CREATE TABLE statement from columns\n *\n * Used internally by getAllSchemas() to regenerate DDL after merging\n * columns from multiple STI subtypes that share the same table.\n *\n * @param tableName - Name of the table\n * @param columns - Column definitions\n * @returns DDL CREATE TABLE statement\n */\nexport function generateDDLFromColumns(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n isSTI = false,\n engine?: DatabaseEngine,\n): string {\n let sql = `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(tableName)} (\\n`;\n\n const columnLines: string[] = [];\n for (const [columnName, columnDef] of Object.entries(columns)) {\n const parts: string[] = [];\n\n // Column name and type\n const strategy = engine ? getDDLStrategy(engine) : undefined;\n const columnType = strategy\n ? strategy.mapType(columnDef.type)\n : columnDef.type;\n parts.push(` ${quoteIdentifier(columnName)} ${columnType}`);\n\n // Primary key\n if (columnDef.primaryKey) {\n parts.push('PRIMARY KEY');\n }\n\n // Not null constraint\n if (columnDef.notNull) {\n parts.push('NOT NULL');\n }\n\n // Unique constraint (skip if primary key already implies uniqueness)\n if (columnDef.unique && !columnDef.primaryKey) {\n parts.push('UNIQUE');\n }\n\n // Default value\n if (columnDef.defaultValue !== undefined) {\n const defaultSQL = strategy\n ? strategy.formatDefaultValue(columnDef.defaultValue, columnDef.type)\n : formatDefaultValue(columnDef.defaultValue, columnDef.type);\n parts.push(`DEFAULT ${defaultSQL}`);\n }\n\n columnLines.push(parts.join(' '));\n }\n\n sql += columnLines.join(',\\n');\n\n // Add UNIQUE constraint for UPSERT operations\n // For STI tables: UNIQUE(slug, context, _meta_type) - different types can have same slug+context\n // For non-STI tables: UNIQUE(slug, context)\n if (columns.slug && columns.context) {\n if (isSTI && columns._meta_type) {\n sql += ',\\n UNIQUE(slug, context, _meta_type)';\n } else {\n sql += ',\\n UNIQUE(slug, context)';\n }\n }\n\n sql += '\\n);';\n\n return sql;\n}\n\n/**\n * Format default value for SQL DDL.\n *\n * Thin wrapper over the shared, injection-safe formatter\n * (`schema/sql-identifiers.ts`) so the registry schema-builder uses the same\n * rules as the DDL strategies and schema generator: an allowlist of SQL\n * keyword/function defaults (not \"contains `(`\"), type-driven literal quoting,\n * and no folding of a literal string `\"null\"` into the SQL NULL keyword.\n *\n * @param value - Default value\n * @param type - Column SQL type\n * @returns Formatted SQL default value\n */\nexport function formatDefaultValue(value: unknown, type: string): string {\n return formatDefaultValueShared(value, type);\n}\n\n/**\n * Options for {@link fieldsToColumns}.\n */\nexport interface FieldsToColumnsOptions {\n /**\n * Shape the columns for a single-table-inheritance table.\n *\n * An STI table holds the union of every subtype's fields, so a column that\n * only one subtype declares must stay nullable — rows of sibling subtypes\n * never populate it. This matches `generateSTISchemaFromManifest`, which\n * emits `notNull: false` for every non-system column on an STI table.\n * Declared defaults are still emitted.\n */\n stiUnionColumns?: boolean;\n}\n\n/**\n * Convert a Map of field definitions to column definitions\n *\n * Used by getAllSchemas() to generate columns from fields when a class\n * has no pre-generated schema (e.g., STI subclasses registered from manifest).\n *\n * `required`, `default`, and `description` are read from either the top level\n * or `_meta`: registry-sourced fields normalize them into `_meta`, so reading\n * only the top level dropped NOT NULL and DEFAULT for every such field\n * (#2372).\n *\n * @param fields - Map of field name to field definition\n * @param options - Table-shape options (see {@link FieldsToColumnsOptions})\n * @returns Record of column name to column definition\n * @private\n */\nexport function fieldsToColumns(\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columns: Record<string, ColumnDefinition> = {};\n\n for (const [fieldName, fieldDef] of fields) {\n // Skip id, timestamps - they're on the base table\n if (\n fieldName === 'id' ||\n fieldName === 'created_at' ||\n fieldName === 'updated_at' ||\n fieldName === 'slug' ||\n fieldName === 'context'\n ) {\n continue;\n }\n\n // Skip transient fields (non-persisted)\n if (fieldDef.transient || fieldDef._meta?.transient) {\n continue;\n }\n\n // Skip relationship fields that don't create columns\n // oneToMany and manyToMany are relationship metadata, not actual database columns\n if (fieldDef.type === 'oneToMany' || fieldDef.type === 'manyToMany') {\n continue;\n }\n\n // Skip meta fields - they're stored in _meta_data JSONB column\n if (fieldDef.type === 'meta') {\n continue;\n }\n\n // Map field type to SQL type\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef.type === 'crossPackageRef' &&\n (fieldDef._meta?.idType === 'text' ||\n (fieldDef as unknown as { idType?: string }).idType === 'text')\n ? 'TEXT'\n : mapFieldTypeToSQL(fieldDef.type));\n const normalizedSqlType = String(sqlType).toUpperCase() as SQLDataType;\n const referenceKind = getReferenceKind(fieldDef);\n\n const required = readFieldAttribute(fieldDef, 'required');\n const defaultValue = readFieldAttribute(fieldDef, 'default');\n const description = readFieldAttribute(fieldDef, 'description');\n\n const column: ColumnDefinition = {\n type: normalizedSqlType,\n referenceKind,\n notNull: options?.stiUnionColumns\n ? false\n : fieldDef._meta?.nullable\n ? false\n : Boolean(required),\n unique: fieldDef._meta?.unique || false,\n description: description as string | undefined,\n };\n\n // Handle default values\n if (\n defaultValue !== undefined &&\n shouldEmitDefault(fieldDef, normalizedSqlType, defaultValue)\n ) {\n column.defaultValue = defaultValue;\n }\n\n // Handle foreign keys\n if (fieldDef.type === 'foreignKey' && fieldDef.related) {\n const [table, columnName = 'id'] = fieldDef.related.split('.');\n const fieldMeta = fieldDef._meta as\n | {\n onDelete?: ForeignKeyAction;\n onUpdate?: ForeignKeyAction;\n }\n | undefined;\n column.foreignKey = {\n table: classnameToTablename(table),\n column: columnName,\n onDelete: fieldMeta?.onDelete ?? 'CASCADE',\n onUpdate: fieldMeta?.onUpdate ?? 'CASCADE',\n };\n }\n\n // Use snake_case for column names\n columns[toSnakeCase(fieldName)] = column;\n }\n\n return columns;\n}\n\n/**\n * Map field type to SQL data type\n * @private\n */\nexport function mapFieldTypeToSQL(\n fieldType: FieldDefinition['type'],\n): SQLDataType {\n switch (fieldType) {\n case 'text':\n return 'TEXT';\n case 'integer':\n return 'INTEGER';\n case 'decimal':\n return 'REAL';\n case 'boolean':\n return 'BOOLEAN';\n case 'datetime':\n return 'TIMESTAMP';\n case 'json':\n return 'JSON';\n case 'foreignKey':\n return 'UUID';\n case 'crossPackageRef':\n return 'UUID';\n default:\n return 'TEXT';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoCA,IAAM,+BAA6D;CACjE;CACA,qBAAqB,aAAa,cAChC,eAAe,kBAAkB,aAAa,SAAS;CACzD,sBAAsB,cACpB,eAAe,oBAAoB,SAAS;AAChD;AAEA,SAAS,+BACP,WACA,SACkC;CAClC,MAAM,aAAa,eAAe,mBAAmB,SAAS;CAC9D,IAAI,CAAC,WAAW,MACd,OAAO;CAGT,KAAK,MAAM,CAAC,WAAW,YAAY,YAAY;EAC7C,IAAI,CAAC,SAAS,SACZ;EAGF,MAAM,aAAa,YAAY,SAAS;EACxC,MAAM,WAAW,QAAQ;EACzB,IAAI,CAAC,UACH;EAGF,MAAM,gBAAgB,iBAAiB,OAA0B;EACjE,QAAQ,cAAc;GACpB,GAAG;GACH,MAAM,OAAO,QAAQ,OAAO,CAAC,CAAC,YAAY;GAC1C,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;EAC3C;CACF;CAEA,OAAO;AACT;AAEA,SAAS,yBACP,WACA,eACA,QACA,SACkC;CAClC,MAAM,eAAe,EAAE,GAAI,iBAAiB,CAAC,EAAG;CAEhD,IAAI,OAAO,OAAO,GAAG;EACnB,MAAM,eAAe,gBAAgB,QAAQ,OAAO;EACpD,KAAK,MAAM,CAAC,YAAY,cAAc,OAAO,QAAQ,YAAY,GAC/D,IAAI,CAAC,aAAa,aAChB,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C,MAAM,WAAW,mBAAmB,UAAU,UAAU;EACxD,MAAM,eAAe,mBAAmB,UAAU,SAAS;EAC3D,MAAM,cAAc,mBAAmB,UAAU,aAAa;EAE9D,MAAM,SAA2B;GAC/B,MAAM;GACN;GACA,SAAS,SAAS,kBACd,QACA,SAAS,OAAO,WACd,QACA,QAAQ,QAAQ;GACtB,QAAQ,SAAS,OAAO,UAAU;GACrB;EACf;EAGA,IACE,iBAAiB,KAAA,KACjB,kBAAkB,UAAU,mBAAmB,YAAY,GAE3D,OAAO,eAAe;EAIxB,IAAI,SAAS,SAAS,gBAAgB,SAAS,SAAS;GACtD,MAAM,CAAC,OAAO,aAAa,QAAQ,SAAS,QAAQ,MAAM,GAAG;GAC7D,MAAM,YAAY,SAAS;GAM3B,OAAO,aAAa;IAClB,OAAO,qBAAqB,KAAK;IACjC,QAAQ;IACR,UAAU,WAAW,YAAY;IACjC,UAAU,WAAW,YAAY;GACnC;EACF;EAGA,QAAQ,YAAY,SAAS,KAAK;CACpC;CAEA,OAAO;AACT;;;;;AAMA,SAAgB,kBACd,WACa;CACb,QAAQ,WAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,cACH,OAAO;EACT,KAAK,mBACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
1
+ {"version":3,"file":"schema-builder.js","names":[],"sources":["../../src/registry/schema-builder.ts"],"sourcesContent":["/**\n * Schema building logic for the SMRT ObjectRegistry.\n *\n * Extracted from registry.ts as part of issue #1006.\n */\n\nimport { ObjectRegistry } from '../registry';\nimport type { FieldDefinition } from '../scanner/types.js';\nimport { conflictIndexName } from '../schema/conflict-target.js';\nimport { getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport {\n renderForeignKeyConstraint,\n schemaForeignKeys,\n} from '../schema/foreign-key-ddl.js';\nimport {\n requireForeignKeyAction,\n resolveForeignKeyDeleteAction,\n} from '../schema/foreign-key-policy.js';\nimport { shortenIdentifier } from '../schema/index-utils.js';\nimport {\n formatDefaultValue as formatDefaultValueShared,\n quoteIdentifier,\n} from '../schema/sql-identifiers.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaDefinition,\n SQLDataType,\n} from '../schema/types.js';\nimport { classnameToTablename, toSnakeCase } from '../utils';\nimport {\n type CollectionRegistrationLookup,\n isCollectionRegistration,\n} from './collection-resolution';\nimport { readFieldAttribute } from './manifest-field-merge';\nimport { findClass } from './name-resolver';\nimport { getClasses, getCollectionTableNames } from './shared-state';\nimport type { RegisteredClass } from './types';\n\ntype ForeignKeyAction = NonNullable<\n NonNullable<ColumnDefinition['foreignKey']>['onDelete']\n>;\n\nconst collectionRegistrationLookup: CollectionRegistrationLookup = {\n findClass,\n findClassInPackage: (packageName, className) =>\n ObjectRegistry.getClassInPackage(packageName, className),\n getInheritanceChain: (className) =>\n ObjectRegistry.getInheritanceChain(className),\n};\n\nfunction applyDecoratorSqlTypeOverrides(\n className: string,\n columns: Record<string, ColumnDefinition>,\n): Record<string, ColumnDefinition> {\n const decorators = ObjectRegistry.getFieldDecorators(className);\n if (!decorators.size) {\n return columns;\n }\n\n for (const [fieldName, options] of decorators) {\n if (!options?.sqlType) {\n continue;\n }\n\n const columnName = toSnakeCase(fieldName);\n const existing = columns[columnName];\n if (!existing) {\n continue;\n }\n\n const referenceKind = getReferenceKind(options as FieldDefinition);\n columns[columnName] = {\n ...existing,\n type: String(options.sqlType).toUpperCase() as SQLDataType,\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n\n return columns;\n}\n\nfunction mergeRuntimeFieldColumns(\n className: string,\n schemaColumns: Record<string, ColumnDefinition> | undefined,\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columnsToUse = { ...(schemaColumns || {}) };\n\n if (fields.size > 0) {\n const fieldColumns = fieldsToColumns(fields, options);\n for (const [columnName, columnDef] of Object.entries(fieldColumns)) {\n if (!columnsToUse[columnName]) {\n columnsToUse[columnName] = columnDef;\n }\n }\n\n for (const [fieldName, fieldDef] of fields) {\n const columnName = toSnakeCase(fieldName);\n const existing = columnsToUse[columnName];\n if (!existing) {\n continue;\n }\n\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef as unknown as { sqlType?: string }).sqlType;\n const referenceKind = getReferenceKind(fieldDef);\n columnsToUse[columnName] = {\n ...existing,\n ...(sqlType\n ? { type: String(sqlType).toUpperCase() as SQLDataType }\n : {}),\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n }\n\n applyDecoratorSqlTypeOverrides(className, columnsToUse);\n return columnsToUse;\n}\n\nfunction getReferenceKind(\n fieldDef: FieldDefinition,\n): ColumnDefinition['referenceKind'] | undefined {\n if (\n (\n fieldDef as unknown as {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField ||\n fieldDef._meta?.__tenancy?.isTenantIdField\n ) {\n return 'tenantId';\n }\n\n if (fieldDef.type === 'foreignKey') {\n return 'foreignKey';\n }\n\n if (fieldDef.type === 'crossPackageRef') {\n return 'crossPackageRef';\n }\n\n return undefined;\n}\n\nfunction shouldEmitDefault(\n fieldDef: FieldDefinition,\n sqlType: SQLDataType,\n defaultValue: unknown,\n) {\n return !(\n getReferenceKind(fieldDef) === 'tenantId' &&\n sqlType === 'UUID' &&\n defaultValue === ''\n );\n}\n\n/**\n * Fallback base columns for a table whose contributing class carries no\n * manifest columns.\n *\n * These mirror what the manifest schema generators emit for the same table\n * (`generateSchemaFromManifest` / `generateSTISchemaFromManifest`), so a table\n * assembled from runtime field metadata alone has the same NOT NULL and\n * DEFAULT shape as one assembled from a manifest. Divergence here is what made\n * the merged table shape depend on which class registered first (#2372).\n */\nfunction createBaseColumns(\n registered: {\n config?: { idType?: 'uuid' | 'text' };\n },\n isSTI: boolean,\n): Record<string, ColumnDefinition> {\n const baseColumns: Record<string, ColumnDefinition> = {\n id: {\n type: registered.config?.idType === 'text' ? 'TEXT' : 'UUID',\n primaryKey: true,\n notNull: true,\n referenceKind: 'id',\n },\n slug: { type: 'TEXT', notNull: true },\n context: { type: 'TEXT', notNull: true, defaultValue: '' },\n created_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n updated_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n };\n\n // STI tables also carry the discriminator and the meta payload column\n // (issue #690: db:diff needs them to detect schema changes).\n if (isSTI) {\n baseColumns._meta_type = { type: 'TEXT', notNull: true };\n baseColumns._meta_data = { type: 'JSON', notNull: false };\n }\n\n return baseColumns;\n}\n\n/**\n * Get cached schema definition for a registered class\n *\n * @param name - Name of the registered class\n * @returns Schema definition or undefined if not found\n * @example\n * ```typescript\n * const schema = getSchema('Product');\n * console.log(schema.tableName); // 'products'\n * console.log(schema.ddl); // 'CREATE TABLE...'\n * ```\n */\nexport function getSchema(name: string): SchemaDefinition | undefined {\n // Issue #951: Use findClass for multi-strategy lookup\n const registered = findClass(name);\n return registered?.schema;\n}\n\n/**\n * Get SQL DDL statement for a registered class\n *\n * @param name - Name of the registered class\n * Cached manifest DDL contains abstract types and is not safe to execute on\n * PostgreSQL. New executable paths must pass a target engine. Omitting it is\n * retained for backward compatibility with consumers that only inspect the\n * legacy engine-neutral manifest string.\n *\n * @param engine - Database engine that will execute the DDL\n * @returns Engine-specific SQL DDL, or the legacy cached DDL when omitted\n * @example\n * ```typescript\n * const ddl = ObjectRegistry.getSchemaDDL('Product', 'postgres');\n * await db.query(ddl);\n * ```\n */\nexport function getSchemaDDL(\n name: string,\n engine?: DatabaseEngine,\n): string | undefined {\n const schema = getSchema(name);\n if (!schema) return undefined;\n if (engine && Object.keys(schema.columns).length === 0) {\n throw new Error(\n `Cannot materialize schema '${name}' for ${engine}: the manifest has no structured columns`,\n );\n }\n return engine\n ? getDDLStrategy(engine).generateCreateTable(schema)\n : schema.ddl;\n}\n\n/**\n * Get table name for a registered class\n *\n * @param name - Name of the registered class\n * @returns Table name or undefined if not found\n * @example\n * ```typescript\n * const tableName = getTableName('Product');\n * console.log(tableName); // 'products'\n * ```\n */\nexport function getTableName(name: string): string | undefined {\n // Check if this is a collection class - collections have their own tableName mapping\n const collectionTableName = getCollectionTableNames().get(name);\n if (collectionTableName) {\n return collectionTableName;\n }\n\n // For STI classes, return the STI base class's table name.\n // R5-canon: `getSTIBase` returns the qualified name; resolve `name`\n // (which may be simple) to its registration's qualified form for the\n // comparison.\n const stiBase = ObjectRegistry.getSTIBase(name);\n const registered = ObjectRegistry.getClass(name);\n const qualifiedName = registered?.qualifiedName ?? registered?.name ?? name;\n if (stiBase && stiBase !== qualifiedName) {\n return getSchema(stiBase)?.tableName;\n }\n return getSchema(name)?.tableName;\n}\n\nfunction withConflictIndex(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n indexes: IndexDefinition[],\n conflictColumns: string[],\n): IndexDefinition[] {\n if (\n conflictColumns.length === 0 ||\n !conflictColumns.every((column) => columns[column])\n ) {\n return indexes;\n }\n\n // `ON CONFLICT (id)` binds to the primary-key constraint itself; a second\n // unique index over the primary key column set adds nothing (#2359, A5).\n // Kept in step with SchemaGenerator.conflictColumnsArePrimaryKey().\n const primaryKeyColumns = Object.entries(columns)\n .filter(([, column]) => column.primaryKey === true)\n .map(([name]) => name);\n if (\n primaryKeyColumns.length > 0 &&\n primaryKeyColumns.length === conflictColumns.length &&\n primaryKeyColumns.every((column) => conflictColumns.includes(column))\n ) {\n return indexes;\n }\n\n const hasConflictIndex = indexes.some(\n (index) =>\n index.unique === true &&\n !index.where &&\n !index.jsonPath &&\n index.columns.length === conflictColumns.length &&\n index.columns.every((column) => conflictColumns.includes(column)),\n );\n if (hasConflictIndex) return indexes;\n\n // Same stable naming as SchemaGenerator (`schema/conflict-target.ts`), so\n // a manifest built before the runtime learned the tenant-aware default\n // (#2360) has its stale `<table>_slug_context_idx` REPLACED in place here\n // — the differ then swaps the live index by name — instead of a second,\n // suffixed unique index being appended beside the old global one.\n const tenantColumn = Object.entries(columns).find(\n ([, column]) => column.referenceKind === 'tenantId',\n )?.[0];\n // The composed name can exceed PostgreSQL's 63-byte limit on a long table.\n // Shortening here (rather than inside conflictIndexName) keeps the generator\n // paths, which run enforceIdentifierLimits() over their whole index list,\n // and this migrate leg agreeing on the final name (#2374).\n const name = shortenIdentifier(\n conflictIndexName(tableName, conflictColumns, tenantColumn),\n );\n const conflictIndex: IndexDefinition = {\n name,\n columns: conflictColumns,\n unique: true,\n };\n if (indexes.some((index) => index.name === name)) {\n return indexes.map((index) =>\n index.name === name ? conflictIndex : index,\n );\n }\n return [...indexes, conflictIndex];\n}\n\n/**\n * A registered class that contributes columns to one physical table.\n *\n * For a single-table-inheritance hierarchy every class in the hierarchy is a\n * contributor to the same table.\n */\ninterface TableContributor {\n registered: RegisteredClass;\n simpleName: string;\n qualifiedName: string;\n isSTI: boolean;\n /** True when this class is the STI base that owns the table. */\n isSTIBase: boolean;\n /** Inheritance depth; ancestors sort before descendants. */\n depth: number;\n /** Conflict-column lookup key (the STI base for STI members). */\n conflictKey: string;\n}\n\n/**\n * A merged physical table assembled from every class that contributes to it.\n */\ninterface MergedTableSchema {\n tableName: string;\n columns: Record<string, ColumnDefinition>;\n indexes: IndexDefinition[];\n ddl: string;\n isSTI: boolean;\n conflictColumns: string[];\n}\n\nfunction applyContributorForeignKeys(\n tableSchema: MergedTableSchema,\n contributor: TableContributor,\n): void {\n const conflictColumns = new Set(tableSchema.conflictColumns);\n for (const [fieldName, field] of contributor.registered.fields) {\n if (field.type !== 'foreignKey' || !field.related) continue;\n const columnName = toSnakeCase(fieldName);\n const column = tableSchema.columns[columnName];\n if (!column) continue;\n if (\n field._meta?.__tenancy?.isTenantIdField === true ||\n (\n field as FieldDefinition & {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField === true\n ) {\n column.foreignKey = undefined;\n continue;\n }\n const [targetName, declaredTargetColumn] = field.related.split('.');\n const targetBase = ObjectRegistry.getSTIBase(targetName) || targetName;\n const registeredTarget = ObjectRegistry.getClass(targetBase);\n const targetColumn =\n declaredTargetColumn ||\n Array.from(ObjectRegistry.getFields(targetBase).entries()).find(\n ([, targetField]) => targetField._meta?.primaryKey === true,\n )?.[0] ||\n 'id';\n if (registeredTarget && !field._meta?.sqlType) {\n const targetColumnName = toSnakeCase(targetColumn);\n const targetColumnType =\n registeredTarget.schema?.columns?.[targetColumnName]?.type ||\n (targetColumnName === 'id'\n ? registeredTarget.config.idType === 'text'\n ? 'TEXT'\n : 'UUID'\n : undefined);\n if (targetColumnType) {\n column.type = targetColumnType;\n }\n }\n if (field._meta?.constraint === false) {\n column.foreignKey = undefined;\n continue;\n }\n // A manifest may carry explicit actions that predate or differ from the\n // runtime decorator defaults. Merging runtime fields must not erase them.\n // The fallback produced from runtime fields, however, must be replaced so\n // conflict columns receive the same default CASCADE as app-side cleanup.\n const manifestForeignKey =\n contributor.registered.schema?.columns?.[columnName]?.foreignKey;\n if (manifestForeignKey) {\n column.foreignKey = manifestForeignKey;\n continue;\n }\n // A decorator-only runtime field has no authoritative physical target\n // until that target is registered. Scanner-produced manifests clear this\n // shape too; only an explicit manifest FK above may survive unloaded\n // runtime classes (the manifest-authority contract from #1120).\n if (!registeredTarget) {\n column.foreignKey = undefined;\n continue;\n }\n const targetTable =\n ObjectRegistry.getTableName(targetBase) ||\n classnameToTablename(targetBase);\n const { action } = resolveForeignKeyDeleteAction({\n declared: field._meta?.onDelete,\n isConflictColumn: conflictColumns.has(columnName),\n isTenantIdField: false,\n });\n column.foreignKey = {\n table: targetTable,\n column: toSnakeCase(targetColumn),\n onDelete: action,\n onUpdate: 'CASCADE',\n ...(typeof field._meta?.constraint === 'object'\n ? { engines: [...field._meta.constraint.engines] }\n : {}),\n };\n }\n}\n\n/**\n * Resolve the physical table a registered class writes to.\n *\n * STI subclasses are folded onto their base's table. Returns `undefined` when\n * the class has no table (for example an unresolvable manifest stub).\n *\n * R5-canon: STI lookups use the qualified key so a colliding simple name in\n * another package cannot yield the wrong table strategy or STI base and move\n * this class's columns under that other package's table.\n */\nfunction resolveContributorTable(\n registered: RegisteredClass,\n fallbackName: string,\n): { tableName: string; contributor: TableContributor } | undefined {\n const simpleName = registered.name || fallbackName;\n const qualifiedName = registered.qualifiedName ?? simpleName;\n\n // STI subclasses loaded from external manifests can arrive with a null\n // tableName; registerFromManifest() then derives one from the class name.\n // Adopt the STI base's tableName instead so the subclass lands on the\n // shared table (issue #703).\n if (!registered.schema?.tableName && registered.extends) {\n if (ObjectRegistry.getTableStrategy(qualifiedName) === 'sti') {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName && stiBaseName !== qualifiedName) {\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n if (!registered.schema) {\n registered.schema = {\n tableName: '',\n ddl: '',\n columns: {},\n indexes: [],\n triggers: [],\n foreignKeys: [],\n dependencies: [],\n version: '',\n };\n }\n registered.schema.tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n if (!registered.schema?.tableName) {\n return undefined;\n }\n\n let tableName = registered.schema.tableName;\n const tableStrategy = ObjectRegistry.getTableStrategy(qualifiedName);\n const isSTI = tableStrategy === 'sti';\n let isSTIBase = isSTI;\n let conflictKey = qualifiedName;\n\n if (isSTI) {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName) {\n conflictKey = stiBaseName;\n if (stiBaseName !== qualifiedName) {\n isSTIBase = false;\n // STI subclasses serialize to the base class's table even when they\n // carry a tableName of their own (issue #693).\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n return {\n tableName,\n contributor: {\n registered,\n simpleName,\n qualifiedName,\n isSTI,\n isSTIBase,\n depth: ObjectRegistry.getInheritanceChain(qualifiedName).length,\n conflictKey,\n },\n };\n}\n\n/**\n * Order the classes that share one table deterministically.\n *\n * The first contributor seeds the table: it supplies the base columns, the\n * `idType`, the conflict columns and the cached DDL, and its columns win every\n * merge conflict. Registration order must not decide that, or the same\n * hierarchy yields a different table shape depending on which class a manifest\n * happens to list first — child-first dropped NOT NULL and DEFAULT from the\n * base columns (#2372).\n *\n * Order: the STI base first, then ancestors before descendants, then by\n * qualified name so the result is a total order.\n */\nfunction sortTableContributors(contributors: TableContributor[]) {\n return [...contributors].sort((a, b) => {\n if (a.isSTIBase !== b.isSTIBase) {\n return a.isSTIBase ? -1 : 1;\n }\n if (a.depth !== b.depth) {\n return a.depth - b.depth;\n }\n return a.qualifiedName.localeCompare(b.qualifiedName);\n });\n}\n\n/**\n * Assemble every physical table from the classes that contribute to it.\n *\n * Shared by {@link getAllSchemas} and {@link getAllSchemasAsDefinitions} so\n * both produce the same merged shape. The result depends only on what is\n * registered, never on the order it was registered in.\n */\nfunction buildMergedTableSchemas(): Record<string, MergedTableSchema> {\n // Pass 1: group contributing classes by physical table.\n const contributorsByTable = new Map<string, TableContributor[]>();\n\n for (const [className, registered] of getClasses()) {\n // Collection classes have no table of their own; their schemas carry\n // collection properties (loaded, options, ...) rather than columns.\n if (\n isCollectionRegistration(\n className,\n registered,\n collectionRegistrationLookup,\n )\n ) {\n continue;\n }\n\n const resolved = resolveContributorTable(registered, className);\n if (!resolved) {\n continue;\n }\n\n const existing = contributorsByTable.get(resolved.tableName);\n if (existing) {\n existing.push(resolved.contributor);\n } else {\n contributorsByTable.set(resolved.tableName, [resolved.contributor]);\n }\n }\n\n // Pass 2: merge each table's contributors in deterministic order.\n const tableSchemas: Record<string, MergedTableSchema> = {};\n\n for (const [tableName, contributors] of contributorsByTable) {\n for (const contributor of sortTableContributors(contributors)) {\n const { registered, simpleName, isSTI } = contributor;\n const conflictColumns = ObjectRegistry.getConflictColumns(\n contributor.conflictKey,\n );\n\n // The manifest schema stays authoritative for the columns it defines.\n // Runtime field metadata backfills columns the manifest never had (for\n // example tenantScoped injections) and applies explicit sqlType\n // overrides, without erasing richer manifest metadata.\n const columnsToUse = mergeRuntimeFieldColumns(\n simpleName,\n registered.schema?.columns,\n registered.fields,\n { stiUnionColumns: isSTI, conflictColumns },\n );\n\n let tableSchema = tableSchemas[tableName];\n if (!tableSchema) {\n tableSchema = {\n tableName,\n columns: {\n ...createBaseColumns(registered, isSTI),\n ...columnsToUse,\n },\n indexes: [],\n ddl: registered.schema?.ddl || '',\n isSTI,\n conflictColumns,\n };\n tableSchemas[tableName] = tableSchema;\n } else {\n // Another class sharing this table (STI): add only columns the\n // seeding contributor did not already define.\n for (const [colName, colDef] of Object.entries(columnsToUse)) {\n if (!tableSchema.columns[colName]) {\n tableSchema.columns[colName] = colDef;\n }\n }\n }\n\n applyContributorForeignKeys(tableSchema, contributor);\n\n // Merge indexes, keeping the first definition of each name.\n const schemaIndexes = registered.schema?.indexes;\n if (schemaIndexes && schemaIndexes.length > 0) {\n const existingNames = new Set(\n tableSchema.indexes.map((index) => index.name),\n );\n for (const index of schemaIndexes) {\n // Legacy string-format indexes carry no columns and cannot be merged.\n if (typeof index === 'string') {\n continue;\n }\n if (!existingNames.has(index.name)) {\n tableSchema.indexes.push(index);\n existingNames.add(index.name);\n }\n }\n }\n }\n }\n\n return tableSchemas;\n}\n\n/**\n * Get all pre-generated schemas for explicit adapter bootstrap paths.\n *\n * Returns schemas in SDK SchemaProvider format for all registered classes.\n * Tooling and test helpers can pass these to `getDatabase()` when they want\n * to bootstrap schema before runtime. Core runtime no longer does this\n * implicitly.\n *\n * @returns Record of table names to schema definitions\n * @example\n * ```typescript\n * const schemas = ObjectRegistry.getAllSchemas('json');\n * const db = await getDatabase({ type: 'json', url: './data', schemas });\n * ```\n */\nexport function getAllSchemas(\n engine?: DatabaseEngine,\n): Record<string, { tableName: string; ddl: string; indexes?: string[] }> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to output format, regenerating DDL for merged schemas\n const schemas: Record<\n string,\n { tableName: string; ddl: string; indexes?: string[] }\n > = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n const engineIndexes = engine\n ? withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n )\n : tableSchema.indexes;\n const mergedSchema: SchemaDefinition = {\n tableName,\n ddl: tableSchema.ddl,\n columns: tableSchema.columns,\n indexes: engineIndexes,\n triggers: [],\n foreignKeys: [],\n version: '',\n dependencies: [],\n };\n mergedSchema.foreignKeys = schemaForeignKeys(mergedSchema);\n mergedSchema.dependencies = mergedSchema.foreignKeys\n .map((foreignKey) => foreignKey.referencesTable)\n .filter((dependency) => dependency !== tableName);\n\n // Generate DDL from merged columns (or use original DDL if columns are empty)\n let ddl: string;\n if (Object.keys(tableSchema.columns).length === 0 && tableSchema.ddl) {\n if (engine) {\n throw new Error(\n `Cannot materialize schema '${tableName}' for ${engine}: the manifest has no structured columns`,\n );\n }\n // Preserve legacy inspection of cached engine-neutral DDL. Executable\n // target-engine paths fail above rather than returning unsafe SQL.\n ddl = tableSchema.ddl;\n } else if (Object.keys(tableSchema.columns).length === 0) {\n // Skip schemas with no columns and no original DDL\n continue;\n } else if (engine) {\n // Target-engine materialization must route the complete structured\n // schema through its strategy. In particular, DuckDB/JSON require\n // UNIQUE constraints inline for ON CONFLICT, and every strategy owns\n // CHECK/default/index-expression rendering.\n ddl = getDDLStrategy(engine).generateCreateTable(mergedSchema);\n } else {\n ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n }\n\n // Convert index definitions to SQL strings for SDK compatibility\n let indexSQL: string[] | undefined;\n if (engineIndexes.length > 0) {\n indexSQL = engine\n ? getDDLStrategy(engine).generateIndexes(mergedSchema)\n : engineIndexes.map((idx) => {\n const indexType = idx.unique ? 'UNIQUE INDEX' : 'INDEX';\n const columnList = idx.columns\n .map((col) => quoteIdentifier(col))\n .join(', ');\n return `CREATE ${indexType} IF NOT EXISTS ${quoteIdentifier(\n idx.name,\n )} ON ${quoteIdentifier(tableName)} (${columnList});`;\n });\n }\n\n schemas[tableName] = {\n tableName,\n ddl,\n indexes: indexSQL,\n };\n }\n\n return schemas;\n}\n\n/**\n * Get all registered schemas as SchemaDefinition objects\n *\n * Similar to getAllSchemas(), but returns SchemaDefinition format suitable\n * for use with SchemaComparer (migrations/differ.ts).\n *\n * Key difference: Indexes are kept as IndexDefinition objects instead of\n * being converted to SQL strings.\n *\n * @returns Map of tableName to SchemaDefinition\n */\nexport function getAllSchemasAsDefinitions(): Record<string, SchemaDefinition> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to SchemaDefinition format\n const schemas: Record<string, SchemaDefinition> = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n if (Object.keys(tableSchema.columns).length === 0) {\n continue;\n }\n\n // Generate DDL from columns\n const ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n const foreignKeys = schemaForeignKeys({\n columns: tableSchema.columns,\n foreignKeys: [],\n });\n\n schemas[tableName] = {\n tableName,\n ddl,\n columns: tableSchema.columns,\n indexes: withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n ),\n triggers: [],\n foreignKeys,\n version: '',\n dependencies: foreignKeys\n .map((foreignKey) => foreignKey.referencesTable)\n .filter((dependency) => dependency !== tableName),\n };\n }\n\n return schemas;\n}\n\n/**\n * Generate DDL CREATE TABLE statement from columns\n *\n * Used internally by getAllSchemas() to regenerate DDL after merging\n * columns from multiple STI subtypes that share the same table.\n *\n * @param tableName - Name of the table\n * @param columns - Column definitions\n * @returns DDL CREATE TABLE statement\n */\nexport function generateDDLFromColumns(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n isSTI = false,\n engine?: DatabaseEngine,\n): string {\n let sql = `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(tableName)} (\\n`;\n\n const columnLines: string[] = [];\n for (const [columnName, columnDef] of Object.entries(columns)) {\n const parts: string[] = [];\n\n // Column name and type\n const strategy = engine ? getDDLStrategy(engine) : undefined;\n const columnType = strategy\n ? strategy.mapType(columnDef.type)\n : columnDef.type;\n parts.push(` ${quoteIdentifier(columnName)} ${columnType}`);\n\n // Primary key\n if (columnDef.primaryKey) {\n parts.push('PRIMARY KEY');\n }\n\n // Not null constraint\n if (columnDef.notNull) {\n parts.push('NOT NULL');\n }\n\n // Unique constraint (skip if primary key already implies uniqueness)\n if (columnDef.unique && !columnDef.primaryKey) {\n parts.push('UNIQUE');\n }\n\n // Default value\n if (columnDef.defaultValue !== undefined) {\n const defaultSQL = strategy\n ? strategy.formatDefaultValue(columnDef.defaultValue, columnDef.type)\n : formatDefaultValue(columnDef.defaultValue, columnDef.type);\n parts.push(`DEFAULT ${defaultSQL}`);\n }\n\n columnLines.push(parts.join(' '));\n }\n for (const foreignKey of schemaForeignKeys({ columns, foreignKeys: [] })) {\n columnLines.push(` ${renderForeignKeyConstraint(tableName, foreignKey)}`);\n }\n\n sql += columnLines.join(',\\n');\n\n // Add UNIQUE constraint for UPSERT operations\n // For STI tables: UNIQUE(slug, context, _meta_type) - different types can have same slug+context\n // For non-STI tables: UNIQUE(slug, context)\n if (columns.slug && columns.context) {\n if (isSTI && columns._meta_type) {\n sql += ',\\n UNIQUE(slug, context, _meta_type)';\n } else {\n sql += ',\\n UNIQUE(slug, context)';\n }\n }\n\n sql += '\\n);';\n\n return sql;\n}\n\n/**\n * Format default value for SQL DDL.\n *\n * Thin wrapper over the shared, injection-safe formatter\n * (`schema/sql-identifiers.ts`) so the registry schema-builder uses the same\n * rules as the DDL strategies and schema generator: an allowlist of SQL\n * keyword/function defaults (not \"contains `(`\"), type-driven literal quoting,\n * and no folding of a literal string `\"null\"` into the SQL NULL keyword.\n *\n * @param value - Default value\n * @param type - Column SQL type\n * @returns Formatted SQL default value\n */\nexport function formatDefaultValue(value: unknown, type: string): string {\n return formatDefaultValueShared(value, type);\n}\n\n/**\n * Options for {@link fieldsToColumns}.\n */\nexport interface FieldsToColumnsOptions {\n /**\n * Shape the columns for a single-table-inheritance table.\n *\n * An STI table holds the union of every subtype's fields, so a column that\n * only one subtype declares must stay nullable — rows of sibling subtypes\n * never populate it. This matches `generateSTISchemaFromManifest`, which\n * emits `notNull: false` for every non-system column on an STI table.\n * Declared defaults are still emitted.\n */\n stiUnionColumns?: boolean;\n /**\n * Physical column names that form the table's natural conflict key.\n * Undeclared delete actions on foreign-key members use the shared CASCADE\n * default, matching app-side relationship cleanup.\n */\n conflictColumns?: readonly string[];\n}\n\n/**\n * Convert a Map of field definitions to column definitions\n *\n * Used by getAllSchemas() to generate columns from fields when a class\n * has no pre-generated schema (e.g., STI subclasses registered from manifest).\n *\n * `required`, `default`, and `description` are read from either the top level\n * or `_meta`: registry-sourced fields normalize them into `_meta`, so reading\n * only the top level dropped NOT NULL and DEFAULT for every such field\n * (#2372).\n *\n * @param fields - Map of field name to field definition\n * @param options - Table-shape options (see {@link FieldsToColumnsOptions})\n * @returns Record of column name to column definition\n * @private\n */\nexport function fieldsToColumns(\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columns: Record<string, ColumnDefinition> = {};\n const conflictColumns = new Set(\n (options?.conflictColumns ?? []).map((column) => toSnakeCase(column)),\n );\n\n for (const [fieldName, fieldDef] of fields) {\n // Skip id, timestamps - they're on the base table\n if (\n fieldName === 'id' ||\n fieldName === 'created_at' ||\n fieldName === 'updated_at' ||\n fieldName === 'slug' ||\n fieldName === 'context'\n ) {\n continue;\n }\n\n // Skip transient fields (non-persisted)\n if (fieldDef.transient || fieldDef._meta?.transient) {\n continue;\n }\n\n // Skip relationship fields that don't create columns\n // oneToMany and manyToMany are relationship metadata, not actual database columns\n if (fieldDef.type === 'oneToMany' || fieldDef.type === 'manyToMany') {\n continue;\n }\n\n // Skip meta fields - they're stored in _meta_data JSONB column\n if (fieldDef.type === 'meta') {\n continue;\n }\n\n // Map field type to SQL type\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef.type === 'crossPackageRef' &&\n (fieldDef._meta?.idType === 'text' ||\n (fieldDef as unknown as { idType?: string }).idType === 'text')\n ? 'TEXT'\n : mapFieldTypeToSQL(fieldDef.type));\n const normalizedSqlType = String(sqlType).toUpperCase() as SQLDataType;\n const referenceKind = getReferenceKind(fieldDef);\n\n const required = readFieldAttribute(fieldDef, 'required');\n const defaultValue = readFieldAttribute(fieldDef, 'default');\n const description = readFieldAttribute(fieldDef, 'description');\n\n const column: ColumnDefinition = {\n type: normalizedSqlType,\n referenceKind,\n notNull: options?.stiUnionColumns\n ? false\n : fieldDef._meta?.nullable\n ? false\n : Boolean(required),\n unique: fieldDef._meta?.unique || false,\n description: description as string | undefined,\n };\n\n // Handle default values\n if (\n defaultValue !== undefined &&\n shouldEmitDefault(fieldDef, normalizedSqlType, defaultValue)\n ) {\n column.defaultValue = defaultValue;\n }\n\n // Handle foreign keys\n if (\n fieldDef.type === 'foreignKey' &&\n fieldDef.related &&\n fieldDef._meta?.constraint !== false &&\n fieldDef._meta?.__tenancy?.isTenantIdField !== true &&\n !(\n fieldDef as FieldDefinition & {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField\n ) {\n const [table, columnName = 'id'] = fieldDef.related.split('.');\n const fieldMeta = fieldDef._meta as\n | {\n onDelete?: ForeignKeyAction;\n onUpdate?: ForeignKeyAction;\n }\n | undefined;\n column.foreignKey = {\n table: classnameToTablename(table),\n column: columnName,\n onDelete: resolveForeignKeyDeleteAction({\n declared: fieldMeta?.onDelete,\n isConflictColumn: conflictColumns.has(toSnakeCase(fieldName)),\n isTenantIdField: false,\n }).action,\n onUpdate:\n fieldMeta?.onUpdate === undefined\n ? 'CASCADE'\n : requireForeignKeyAction(\n fieldMeta.onUpdate,\n `${fieldName} ON UPDATE`,\n ),\n ...(typeof fieldDef._meta?.constraint === 'object'\n ? { engines: [...fieldDef._meta.constraint.engines] }\n : {}),\n };\n }\n\n // Use snake_case for column names\n columns[toSnakeCase(fieldName)] = column;\n }\n\n return columns;\n}\n\n/**\n * Map field type to SQL data type\n * @private\n */\nexport function mapFieldTypeToSQL(\n fieldType: FieldDefinition['type'],\n): SQLDataType {\n switch (fieldType) {\n case 'text':\n return 'TEXT';\n case 'integer':\n return 'INTEGER';\n case 'decimal':\n return 'REAL';\n case 'boolean':\n return 'BOOLEAN';\n case 'datetime':\n return 'TIMESTAMP';\n case 'json':\n return 'JSON';\n case 'foreignKey':\n return 'UUID';\n case 'crossPackageRef':\n return 'UUID';\n default:\n return 'TEXT';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4CA,IAAM,+BAA6D;CACjE;CACA,qBAAqB,aAAa,cAChC,eAAe,kBAAkB,aAAa,SAAS;CACzD,sBAAsB,cACpB,eAAe,oBAAoB,SAAS;AAChD;AAEA,SAAS,+BACP,WACA,SACkC;CAClC,MAAM,aAAa,eAAe,mBAAmB,SAAS;CAC9D,IAAI,CAAC,WAAW,MACd,OAAO;CAGT,KAAK,MAAM,CAAC,WAAW,YAAY,YAAY;EAC7C,IAAI,CAAC,SAAS,SACZ;EAGF,MAAM,aAAa,YAAY,SAAS;EACxC,MAAM,WAAW,QAAQ;EACzB,IAAI,CAAC,UACH;EAGF,MAAM,gBAAgB,iBAAiB,OAA0B;EACjE,QAAQ,cAAc;GACpB,GAAG;GACH,MAAM,OAAO,QAAQ,OAAO,CAAC,CAAC,YAAY;GAC1C,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;EAC3C;CACF;CAEA,OAAO;AACT;AAEA,SAAS,yBACP,WACA,eACA,QACA,SACkC;CAClC,MAAM,eAAe,EAAE,GAAI,iBAAiB,CAAC,EAAG;C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KACjB,kBAAkB,UAAU,mBAAmB,YAAY,GAE3D,OAAO,eAAe;EAIxB,IACE,SAAS,SAAS,gBAClB,SAAS,WACT,SAAS,OAAO,eAAe,SAC/B,SAAS,OAAO,WAAW,oBAAoB,QAC/C,CACE,SAGA,WAAW,iBACb;GACA,MAAM,CAAC,OAAO,aAAa,QAAQ,SAAS,QAAQ,MAAM,GAAG;GAC7D,MAAM,YAAY,SAAS;GAM3B,OAAO,aAAa;IAClB,OAAO,qBAAqB,KAAK;IACjC,QAAQ;IACR,UAAU,8BAA8B;KACtC,UAAU,WAAW;KACrB,kBAAkB,gBAAgB,IAAI,YAAY,SAAS,CAAC;KAC5D,iBAAiB;IACnB,CAAC,CAAC,CAAC;IACH,UACE,WAAW,aAAa,KAAA,IACpB,YACA,wBACE,UAAU,UACV,GAAG,UAAU,WACf;IACN,GAAI,OAAO,SAAS,OAAO,eAAe,WACtC,EAAE,SAAS,CAAC,GAAG,SAAS,MAAM,WAAW,OAAO,EAAE,IAClD,CAAC;GACP;EACF;EAGA,QAAQ,YAAY,SAAS,KAAK;CACpC;CAEA,OAAO;AACT;;;;;AAMA,SAAgB,kBACd,WACa;CACb,QAAQ,WAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,cACH,OAAO;EACT,KAAK,mBACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
@@ -792,13 +792,11 @@ export declare class ObjectRegistry {
792
792
  * Foreign-key cycles (e.g. smrt-chat's ChatMessage.threadId -> ChatThread
793
793
  * and ChatThread.rootMessageId -> ChatMessage) are BROKEN rather than
794
794
  * treated as a fatal error: when a back-edge is encountered the recursion
795
- * stops there, so every class still appears in the returned order. SMRT does
796
- * not emit real DB `FOREIGN KEY` constraints in its generated CREATE TABLE
797
- * DDL, so a table can be created before its cyclic reference target exists —
798
- * the reference is satisfied once both tables are present. This mirrors the
799
- * standard RDBMS approach (create tables first, wire cyclic references
800
- * afterward) and matches SchemaManager.sortByDependencies, which already
801
- * tolerates cycles. See issue #1333.
795
+ * stops there, so every class still appears in the returned order. The schema
796
+ * creation planner then handles physical constraints per engine: SQLite
797
+ * keeps cyclic constraints inline, PostgreSQL defers them until both tables
798
+ * exist, and DuckDB refuses unsupported cycles with actionable guidance.
799
+ * See issues #1333 and #2413.
802
800
  *
803
801
  * @returns Array of class names in initialization order. Every registered
804
802
  * class appears exactly once; cycle back-edges are dropped from the
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAIH,OAAO,EACL,cAAc,EAEd,KAAK,qBAAqB,EAC3B,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,EACV,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,EACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAUhD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAS3C,OAAO,EAIL,KAAK,kBAAkB,EAExB,MAAM,wBAAwB,CAAC;AA8DhC,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,qBAAqB,EACrB,iBAAiB,EAClB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EACV,gBAAgB,EAChB,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACf,MAAM,oBAAoB,CAAC;AAK5B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OA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,CAAC,mBAAmB,IAAI,MAAM,EAAE;IAItC;;;;;;;;;;;;;;;;;;OAkBG;IACH,MAAM,CAAC,yBAAyB,IAAI,sBAAsB;IAI1D;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,MAAM,CAAC,sBAAsB,CAC3B,SAAS,EAAE,MAAM,GAChB,uBAAuB,GAAG,SAAS;IAItC;;;;;;;;OAQG;IACH,MAAM,CAAC,4BAA4B,CACjC,SAAS,EAAE,MAAM,GAChB,qBAAqB,GAAG,SAAS;CAGrC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AACH,wBAAgB,IAAI,CAAC,MAAM,GAAE,iBAAsB,IAMzC,CAAC,SAAS,QAAQ,MAAM,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,MAAM,EACvD,MAAM,CAAC,EACP,mBAAmB,qBAAqB,CAAC,CAAC,CAAC,KAC1C,CAAC,CAmML"}
package/dist/registry.js CHANGED
@@ -1301,13 +1301,11 @@ var ObjectRegistry = class ObjectRegistry {
1301
1301
  * Foreign-key cycles (e.g. smrt-chat's ChatMessage.threadId -> ChatThread
1302
1302
  * and ChatThread.rootMessageId -> ChatMessage) are BROKEN rather than
1303
1303
  * treated as a fatal error: when a back-edge is encountered the recursion
1304
- * stops there, so every class still appears in the returned order. SMRT does
1305
- * not emit real DB `FOREIGN KEY` constraints in its generated CREATE TABLE
1306
- * DDL, so a table can be created before its cyclic reference target exists —
1307
- * the reference is satisfied once both tables are present. This mirrors the
1308
- * standard RDBMS approach (create tables first, wire cyclic references
1309
- * afterward) and matches SchemaManager.sortByDependencies, which already
1310
- * tolerates cycles. See issue #1333.
1304
+ * stops there, so every class still appears in the returned order. The schema
1305
+ * creation planner then handles physical constraints per engine: SQLite
1306
+ * keeps cyclic constraints inline, PostgreSQL defers them until both tables
1307
+ * exist, and DuckDB refuses unsupported cycles with actionable guidance.
1308
+ * See issues #1333 and #2413.
1311
1309
  *
1312
1310
  * @returns Array of class names in initialization order. Every registered
1313
1311
  * class appears exactly once; cycle back-edges are dropped from the
@@ -1339,7 +1337,7 @@ var ObjectRegistry = class ObjectRegistry {
1339
1337
  order.push(className);
1340
1338
  }
1341
1339
  for (const className of graph.keys()) if (!visited.has(className)) visit(className);
1342
- if (cycleMembers.size > 0) logger.warn(`[ObjectRegistry] Foreign-key cycle(s) detected and broken for ordering: ${[...cycleMembers].join(", ")}. Tables are created without strict cyclic ordering; SMRT does not emit DB-level FOREIGN KEY constraints, so this is safe.`);
1340
+ if (cycleMembers.size > 0) logger.warn(`[ObjectRegistry] Foreign-key cycle(s) detected and broken for ordering: ${[...cycleMembers].join(", ")}. Tables are created without strict cyclic ordering; the schema creation planner will apply engine-specific cycle handling.`);
1343
1341
  return order;
1344
1342
  }
1345
1343
  /**