diff --git a/.changeset/34095-upgrade-plan-object-extensions.md b/.changeset/34095-upgrade-plan-object-extensions.md new file mode 100644 index 00000000000..da836463e9d --- /dev/null +++ b/.changeset/34095-upgrade-plan-object-extensions.md @@ -0,0 +1,39 @@ +--- +'@objectstack/metadata-core': patch +'@objectstack/objectql': patch +'@objectstack/cloud-connection': patch +'@objectstack/cli': patch +--- + +fix(metadata-core,objectql,cloud-connection,cli)!: the package upgrade plan counts the fields a package adds through `objectExtensions` + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for an upgrade that changes a field the package adds to an object through `objectExtensions`. Four kinds of upgrade that installed without a question before are now refused, exactly as the same change to a field of an object the package declares is: + +- an extension field retyped to a `needs_confirm` or `destructive` type: `409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED`; +- an extension field dropped while another stored extension field of the same object is added, with no `renamedFrom` linking them: `409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED`, as a suspected rename; +- a stored field dropped from an object's own declaration in the upgraded version while an extension of the same object adds a stored field, or an extension field dropped while the object's own declaration adds one: `409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED`, as a suspected rename. The owned and the extension fields of one object are now one field map, so the two pair; before, they were never compared; +- an extension field that declares `renamedFrom` and whose new type stores no column (a `formula`, for example): `422 VALIDATION_ERROR` with `details.refusals[].reason: 'destructive_type'`, before anything is written, as for an owned field. No token answers this refusal. + +The package upgrade plan (`comparePackageVersions`) read only a version's `objects` and `data`. A field an `objectExtensions` entry adds, retypes or drops was therefore missing from the upgrade preview, from the rows counted per touched column, and from the schema upgrade verdict. A preview of an upgrade that added seven columns through extensions listed no added field, and its rollback listed no removed one. + +Now each side of the comparison is the objects as the registry serves them from that version: the owner's declaration, with every extension's `fields` merged over it by name, in ascending `priority` (`200` when none is declared). The existing rules then apply to an extension field unchanged: + +- an extension field added is listed in `plan.fields.added`, and one dropped in `plan.fields.removed`, with the rows holding a value counted in `environment.columns`; +- an extension field retyped is a type change; `needs_confirm` and `destructive` changes need the confirmation, and a `safe` one does not; +- an extension field dropped while another stored field of the same object is added, with no `renamedFrom` linking them, is a suspected rename and needs the confirmation; a field dropped alone is listed and refused by nothing, as an owned one is. + +An object a version reaches only through an extension (another package owns it) is compared by the fields the extension adds. It is never listed in `plan.objects.added` or `plan.objects.removed`, because the upgrade neither creates nor drops it. `os diff` prints the field changes of such an object under `objects..fields`. + +`PackageUpgradeSide` (`@objectstack/metadata-core`) gains an optional `objectExtensions` list. A caller that builds a side itself passes the version's `objectExtensions` beside its `objects`, read with the same collection reader; a side without the key compares as before. + +Who moves, and the fix for each: + +- An installer upgrading a package whose new version retypes an extension field, or drops a field of an object while another stored field of the same object is added (extension or owned, in either pairing): the `409`. Confirm the findings with the token the refusal names (`--confirm-upgrade ` on `os deploy` and `os package install`); for a suspected rename the refusal names the other way forward too. +- A package author whose new version renames an extension field with `renamedFrom` into a type that stores no column: the `422`. `--confirm-upgrade` does not answer it. Keep a stored type for the renamed field, or carry the values by hand, as the refusal's message says. + +Unchanged: a plan over packages that declare no `objectExtensions` is the same plan as before; seed datasets are compared as before; `fieldPatches` changes display properties only and stays out of the comparison. diff --git a/packages/cli/src/commands/diff.ts b/packages/cli/src/commands/diff.ts index b02482c057c..36e7cb95eb1 100644 --- a/packages/cli/src/commands/diff.ts +++ b/packages/cli/src/commands/diff.ts @@ -101,10 +101,18 @@ function diffObjectsAndSeeds(beforeConfig: any, afterConfig: any): DiffEntry[] { for (const name of plan.objects.removed) entries.push({ type: 'removed', category: 'objects', name, breaking: true }); for (const name of plan.objects.added) entries.push({ type: 'added', category: 'objects', name, breaking: false }); + const beforeObjects = getNames(beforeConfig.objects); const afterObjects = getNames(afterConfig.objects); - for (const [name, beforeObj] of getNames(beforeConfig.objects)) { + // Every object both configs declare, then (#34095) each object the plan + // lists field changes on that a config reaches only through + // `objectExtensions`: the plan compares those too, and they print alike. + const compared = [...beforeObjects.keys()].filter((name) => afterObjects.has(name)); + for (const list of [plan.fields.removed, plan.fields.added, plan.declaredRenames, plan.typeChanges, plan.suspectedRenames]) { + for (const item of list) if (!compared.includes(item.object)) compared.push(item.object); + } + for (const name of compared) { + const beforeObj = beforeObjects.get(name); const afterObj = afterObjects.get(name); - if (!afterObj) continue; const category = `objects.${name}.fields`; const mine = (list: T[]): T[] => list.filter((item) => item.object === name); @@ -138,7 +146,7 @@ function diffObjectsAndSeeds(beforeConfig: any, afterConfig: any): DiffEntry[] { } // Label / ownership changes on the object itself - if (beforeObj.label !== afterObj.label) { + if (beforeObj && afterObj && beforeObj.label !== afterObj.label) { entries.push({ type: 'modified', category: 'objects', diff --git a/packages/cli/test/diff-upgrade-plan.test.ts b/packages/cli/test/diff-upgrade-plan.test.ts index 6ef764a7dbb..135d0c94408 100644 --- a/packages/cli/test/diff-upgrade-plan.test.ts +++ b/packages/cli/test/diff-upgrade-plan.test.ts @@ -178,3 +178,27 @@ describe('os diff — what the upgrade plan adds', () => { ]); }); }); + +describe('os diff — objectExtensions fields, as the plan compares them (#34095)', () => { + const ACCOUNT = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text' } } }; + + it('an extension field added to an object the config owns prints under that object', () => { + const entries = diffStacks( + { objects: [ACCOUNT] }, + { objects: [ACCOUNT], objectExtensions: [{ extend: 'crm_account', fields: { invoiced_amount: { type: 'number' } } }] }, + ); + expect(entries).toEqual([ + { type: 'added', category: 'objects.crm_account.fields', name: 'invoiced_amount', breaking: false, detail: 'optional field added' }, + ]); + }); + + it('an object reached only through an extension prints its field changes, and is never an added or removed object', () => { + const entries = diffStacks( + { objectExtensions: [{ extend: 'crm_contact', fields: { tier: { type: 'text' } } }] }, + { objectExtensions: [{ extend: 'crm_contact', fields: { tier: { type: 'number' } } }] }, + ); + expect(entries).toEqual([ + { type: 'modified', category: 'objects.crm_contact.fields', name: 'tier', breaking: true, detail: 'type changed: text → number' }, + ]); + }); +}); diff --git a/packages/cloud-connection/src/marketplace-install-local-declared-rename.test.ts b/packages/cloud-connection/src/marketplace-install-local-declared-rename.test.ts index a17d620fe7e..96e20778d73 100644 --- a/packages/cloud-connection/src/marketplace-install-local-declared-rename.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-declared-rename.test.ts @@ -290,6 +290,28 @@ describe('a declared rename that cannot be carried is refused 422 before any wri await refusedBefore(door, driver, before); }); + it('`destructive_type` on an extension field: the renamed field an `objectExtensions` entry adds turns a type that stores no column (#34095)', async () => { + // The upgrade plan folds the extension's fields onto `acme_lead`, so the + // destructive retype on the declared rename reaches the planner as it + // does for an owned field: refused by name, which no token answers. + const driver = fakeDriver({ acme_lead: new Set(['id', 'company']) }); + const ext = (version: string, fields: Row) => ({ + id: 'com.acme.ext', namespace: 'acmeext', version, objectExtensions: [{ extend: 'acme_lead', fields }], + }); + const served = { acme_lead: lead({ company: { type: 'text' } }) }; + const door = await mount({ installed: ext('1.0.0', { company: { type: 'text' } }), driver, served }); + const before = ledgerFiles(); + const res = await door.install(makeC({ + manifest: ext('2.0.0', { account_name: { type: 'formula', expression: '1', renamedFrom: ['company'] } }), + })); + expect(res.status).toBe(422); + expect(res.payload.error.code).toBe('VALIDATION_ERROR'); + expect(res.payload.error.details.refusals).toEqual([expect.objectContaining({ + object: 'acme_lead', field: 'account_name', from: ['company'], reason: 'destructive_type', + })]); + await refusedBefore(door, driver, before); + }); + it('`outside_package`: an extension\'s field names a column its own package never contributed (the owner\'s just-dropped key)', async () => { // The owner's table still holds `company` (the owner dropped it); this // package only ever extended the object with `nickname`. diff --git a/packages/cloud-connection/src/marketplace-install-local-upgrade-plan.test.ts b/packages/cloud-connection/src/marketplace-install-local-upgrade-plan.test.ts index 2fa14ac2e7c..629eb6fba31 100644 --- a/packages/cloud-connection/src/marketplace-install-local-upgrade-plan.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-upgrade-plan.test.ts @@ -81,7 +81,11 @@ afterEach(() => { vi.restoreAllMocks(); }); -const fold = (artifact: unknown) => ({ objects: resolveStackCollection(artifact, 'objects'), data: resolveStackCollection(artifact, 'data') }); +const fold = (artifact: unknown) => ({ + objects: resolveStackCollection(artifact, 'objects'), + objectExtensions: resolveStackCollection(artifact, 'objectExtensions'), + data: resolveStackCollection(artifact, 'data'), +}); async function mount(options: { installed?: Row; planUpgrade?: false; columns?: Row[]; overrides?: unknown; registryPackages?: Row[]; driver?: unknown } = {}) { const register = vi.fn(); @@ -494,3 +498,51 @@ describe('step 2c′: the schema upgrade verdict on a managed re-install', () => expect(entry()?.schemaUpgradeConfirmation).toBeUndefined(); }); }); + +describe('step 2c′ judges an objectExtensions field like an owned one (#34095)', () => { + /** The vendor package, adding fields to an object another package owns. */ + const extending = (version: string, fields: Row) => ({ + ...vendorBody(version, { company: { type: 'text' } }), + objectExtensions: [{ extend: 'crm_account', fields }], + }); + + it('a retyped extension field answers 409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED naming it, and writes nothing', async () => { + const door = await mount({ installed: extending('1.0.0', { tier: { type: 'text' } }) }); + const before = ledgerFiles(); + + const res = await door.install(makeC({ manifest: extending('2.0.0', { tier: { type: 'number' } }) })); + + expect(res.status).toBe(409); + expect(res.payload.error.code).toBe('SCHEMA_UPGRADE_CONFIRMATION_REQUIRED'); + expect(res.payload.error.details.findings).toEqual([expect.objectContaining({ + kind: 'type_change', object: 'crm_account', field: 'tier', from: 'text', to: 'number', category: 'needs_confirm', + })]); + expect(door.register).not.toHaveBeenCalled(); + expect(ledgerFiles()).toEqual(before); + }); + + it('an extension field dropped beside one added answers 409 as a suspected rename', async () => { + const door = await mount({ installed: extending('1.0.0', { tier: { type: 'text' } }) }); + const res = await door.install(makeC({ manifest: extending('2.0.0', { segment: { type: 'text' } }) })); + expect(res.status).toBe(409); + expect(res.payload.error.code).toBe('SCHEMA_UPGRADE_CONFIRMATION_REQUIRED'); + expect(res.payload.error.details.findings).toEqual([expect.objectContaining({ + kind: 'suspected_rename', object: 'crm_account', field: 'tier', candidates: [{ field: 'segment', type: 'text' }], + })]); + }); + + it('the dry run lists an added extension field; adding it, or dropping one alone, installs unrefused as an owned field does', async () => { + const door = await mount({ installed: extending('1.0.0', { tier: { type: 'text' } }) }); + const preview = await door.install(makeC({ manifest: extending('2.0.0', { tier: { type: 'text' }, invoiced_amount: { type: 'number' } }), dryRun: true })); + expect(preview.status).toBe(200); + expect(preview.payload.data.plan.fields.added).toEqual([ + { object: 'crm_account', field: 'invoiced_amount', type: 'number', required: false, stored: true }, + ]); + + const added = await door.install(makeC({ manifest: extending('2.0.0', { tier: { type: 'text' }, invoiced_amount: { type: 'number' } }) })); + expect(added.status).toBe(200); + const dropped = await door.install(makeC({ manifest: extending('3.0.0', { tier: { type: 'text' } }) })); + expect(dropped.status).toBe(200); + expect(new LocalManifestSource(dir).read(VENDOR).entry?.schemaUpgradeConfirmation).toBeUndefined(); + }); +}); diff --git a/packages/cloud-connection/src/marketplace-install-rename-planner.ts b/packages/cloud-connection/src/marketplace-install-rename-planner.ts index 49ef60bca83..51c9a6a1d61 100644 --- a/packages/cloud-connection/src/marketplace-install-rename-planner.ts +++ b/packages/cloud-connection/src/marketplace-install-rename-planner.ts @@ -46,9 +46,18 @@ export function convertPackageBodyForward(ctx: PluginContext, manifest: unknown) return typeof ql?.convertPackageBodyForward === 'function' ? ql.convertPackageBodyForward(manifest) : manifest; } -/** One side of a package version comparison, a multi-package artifact folded as `planUpgrade` folds it. */ +/** + * One side of a package version comparison, a multi-package artifact folded as + * `planUpgrade` folds it: `objects`, `objectExtensions` (#34095: the comparison + * merges each extension's fields onto its target, so the verdict judges an + * extension field like an owned one) and `data`. + */ export function packageUpgradeSideOf(artifact: unknown): PackageUpgradeSide { - return { objects: resolveStackCollection(artifact, 'objects'), data: resolveStackCollection(artifact, 'data') }; + return { + objects: resolveStackCollection(artifact, 'objects'), + objectExtensions: resolveStackCollection(artifact, 'objectExtensions'), + data: resolveStackCollection(artifact, 'data'), + }; } /** diff --git a/packages/metadata-core/src/package-upgrade-plan.test.ts b/packages/metadata-core/src/package-upgrade-plan.test.ts index 0b6cba66c55..2c54f383f00 100644 --- a/packages/metadata-core/src/package-upgrade-plan.test.ts +++ b/packages/metadata-core/src/package-upgrade-plan.test.ts @@ -14,6 +14,7 @@ import { typeChangeCategory, upgradePlanSeedDatasets, } from './package-upgrade-plan.js'; +import { schemaUpgradeVerdict } from './package-upgrade-verdict.js'; type Fields = Record>; @@ -199,3 +200,85 @@ describe('seed datasets', () => { expect(plan.seeds.changed).toEqual([]); }); }); + +describe('objectExtensions: an extension field counts like an owned one (#34095)', () => { + // HotCRM's shape: one package owns `crm_account`, another of the same + // artifact adds receivables figures to it through `objectExtensions`. + const ACCOUNT = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text' } } }; + const extending = (fields: Fields, extra: Record = {}) => ({ extend: 'crm_account', fields, ...extra }); + const SUMMARY = { type: 'summary', summaryOperations: { object: 'crm_invoice', field: 'amount', function: 'sum' } }; + + it('an extension field the incoming version adds is listed in fields.added, as an owned one is', () => { + const plan = comparePackageVersions( + { objects: [ACCOUNT] }, + { objects: [ACCOUNT], objectExtensions: [extending({ invoiced_amount: SUMMARY, received_amount: SUMMARY })] }, + ); + expect(plan.fields.added).toEqual([ + { object: 'crm_account', field: 'invoiced_amount', type: 'summary', required: false, stored: true }, + { object: 'crm_account', field: 'received_amount', type: 'summary', required: false, stored: true }, + ]); + expect(plan.objects).toEqual({ added: [], removed: [] }); + }); + + it('the rollback lists the same fields in fields.removed', () => { + const plan = comparePackageVersions( + { objects: [ACCOUNT], objectExtensions: [extending({ invoiced_amount: SUMMARY })] }, + { objects: [ACCOUNT] }, + ); + expect(plan.fields.removed).toEqual([{ object: 'crm_account', field: 'invoiced_amount', type: 'summary', required: false, stored: true }]); + }); + + it('an object reached only through an extension (another package owns it) is compared by the fields added, never listed as an object', () => { + const added = comparePackageVersions({}, { objectExtensions: [extending({ tier: { type: 'text' } })] }); + expect(added.fields.added).toEqual([{ object: 'crm_account', field: 'tier', type: 'text', required: false, stored: true }]); + expect(added.objects).toEqual({ added: [], removed: [] }); + + const removed = comparePackageVersions({ objectExtensions: [extending({ tier: { type: 'text' } })] }, {}); + expect(removed.fields.removed).toEqual([{ object: 'crm_account', field: 'tier', type: 'text', required: false, stored: true }]); + expect(removed.objects).toEqual({ added: [], removed: [] }); + }); + + it('a retyped extension field is a type change, and the verdict asks its confirmation', () => { + const plan = comparePackageVersions( + { objectExtensions: [extending({ tier: { type: 'text' }, score: { type: 'number' } })] }, + { objectExtensions: [extending({ tier: { type: 'number' }, score: { type: 'formula' } })] }, + ); + expect(plan.typeChanges).toEqual([ + { object: 'crm_account', field: 'tier', from: 'text', to: 'number', category: 'needs_confirm' }, + { object: 'crm_account', field: 'score', from: 'number', to: 'formula', category: 'destructive' }, + ]); + expect(schemaUpgradeVerdict('com.acme.o2c', plan).findings.map((f) => f.kind === 'type_change' && `${f.field}:${f.category}`)) + .toEqual(['tier:needs_confirm', 'score:destructive']); + }); + + it('a dropped extension field is listed removed and judged as an owned drop: alone it is refused by nothing, beside an added one it is a suspected rename', () => { + const before = { objects: [ACCOUNT], objectExtensions: [extending({ tier: { type: 'text' } })] }; + const dropped = comparePackageVersions(before, { objects: [ACCOUNT] }); + expect(dropped.fields.removed).toEqual([{ object: 'crm_account', field: 'tier', type: 'text', required: false, stored: true }]); + // The verdict's rule for a removed field (ruling record 6709061297): reported by a dry run, refused by nothing. + expect(schemaUpgradeVerdict('com.acme.o2c', dropped).findings).toEqual([]); + + const replaced = comparePackageVersions(before, { objects: [ACCOUNT], objectExtensions: [extending({ segment: { type: 'text' } })] }); + expect(replaced.suspectedRenames).toEqual([{ object: 'crm_account', field: 'tier', type: 'text', candidates: [{ field: 'segment', type: 'text' }] }]); + expect(schemaUpgradeVerdict('com.acme.o2c', replaced).findings).toEqual([expect.objectContaining({ kind: 'suspected_rename', field: 'tier' })]); + }); + + it('the fields compared are the served ones: the extension with the higher priority writes last', () => { + const ext = (type: string, priority?: number) => extending({ tier: { type } }, priority === undefined ? {} : { priority }); + // Listed low → high, and high → low: the 300 extension's `number` is served either way. + for (const extensions of [[ext('text'), ext('number', 300)], [ext('number', 300), ext('text')]]) { + const plan = comparePackageVersions({ objects: [ACCOUNT], objectExtensions: [ext('text')] }, { objects: [ACCOUNT], objectExtensions: extensions }); + expect(plan.typeChanges).toEqual([{ object: 'crm_account', field: 'tier', from: 'text', to: 'number', category: 'needs_confirm' }]); + } + }); + + it('CONTROL: an owned-field plan is unchanged by the fold', () => { + const before = side({ title: { type: 'text' }, legacy: { type: 'text' } }); + const after = side({ title: { type: 'number' }, fresh: { type: 'text' } }); + const owned = comparePackageVersions(before, after); + // The same pair with empty extension lists, and with an unchanged extension of another object. + const unchanged = { objectExtensions: [{ extend: 'crm_account', fields: { tier: { type: 'text' } } }] }; + expect(JSON.stringify(comparePackageVersions({ ...before, objectExtensions: [] }, { ...after, objectExtensions: [] }))).toBe(JSON.stringify(owned)); + expect(JSON.stringify(comparePackageVersions({ ...before, ...unchanged }, { ...after, ...unchanged }))).toBe(JSON.stringify(owned)); + }); +}); diff --git a/packages/metadata-core/src/package-upgrade-plan.ts b/packages/metadata-core/src/package-upgrade-plan.ts index 3236121f216..8db2829d20c 100644 --- a/packages/metadata-core/src/package-upgrade-plan.ts +++ b/packages/metadata-core/src/package-upgrade-plan.ts @@ -22,16 +22,40 @@ * ## What it reads * * Each side is ONE flat package body, as far as this function is concerned: - * its `objects` (each an object with a `name` and a `fields` map) and its - * `data` (seed datasets). A multi-package artifact is folded by the caller - * with the platform's one collection reader (`resolveStackCollection` in - * `@objectstack/core`; `os diff` folds through the CLI's union stack), so this - * module holds no second reading of `packages[]`. + * its `objects` (each an object with a `name` and a `fields` map), its + * `objectExtensions` (fields it adds to an object, its own or another + * package's) and its `data` (seed datasets). A multi-package artifact is + * folded by the caller with the platform's one collection reader + * (`resolveStackCollection` in `@objectstack/core`; `os diff` folds through + * the CLI's union stack), so this module holds no second reading of + * `packages[]`. + * + * ## Extension fields count like owned ones (#34095) + * + * An upgrade adds the columns of every field its `objectExtensions` add, so a + * comparison that read `objects` alone listed none of them: a preview showed + * no added field while the upgrade added seven columns. Each side's fields of + * an object are therefore the object as the registry serves it from that + * side: the owner's declaration with each extension's `fields` merged over it + * BY NAME, a later writer replacing the whole field, in ascending `priority` + * (`ext.priority ?? 200`), equal priorities in the order the side lists them + * (`mergeObjectDefinitions` in `@objectstack/objectql`, applied by the + * registry's fold). The target is the object whose `name` is the `extend` + * string verbatim, the registry's own key. From there every rule below + * applies unchanged: an extension field added, removed, retyped or renamed is + * listed, and judged by the verdict, exactly as an owned one is. + * + * An object a side reaches ONLY through extensions (another package owns it) + * is compared by the fields the extensions add, and it is never listed as an + * added or removed object: the upgrade neither creates nor drops it. Its + * owner's own fields are not on either side, so they are never listed. + * `fieldPatches` change display keys only and store no column: not compared. * * ## What it reports * * - objects added and removed, by name; - * - fields added and removed, by key, within an object both versions declare; + * - fields added and removed, by key, within an object both versions declare + * (or that a version reaches only through its extensions); * - type changes: a field both versions declare whose `type` differs, with a * drift category ({@link typeChangeCategory}); * - declared renames: a field of the new version whose `renamedFrom` names a @@ -64,10 +88,15 @@ import { canonicalize } from './canonicalize.js'; */ export type UpgradeDriftCategory = 'safe' | 'needs_confirm' | 'destructive'; -/** One side of the comparison: a flat package body's two collections. */ +/** One side of the comparison: a flat package body's three collections. */ export interface PackageUpgradeSide { /** The body's object definitions (`{ name, fields }`). */ objects?: readonly unknown[]; + /** + * The body's object extensions (`ObjectExtensionSchema`: `{ extend, fields, + * priority? }`), whose `fields` merge onto the object `extend` names. + */ + objectExtensions?: readonly unknown[]; /** The body's seed datasets (`SeedSchema`). */ data?: readonly unknown[]; } @@ -152,13 +181,38 @@ function isBag(value: unknown): value is Bag { return typeof value === 'object' && value !== null && !Array.isArray(value); } -/** Objects by name, the LAST declaration of a name winning (`os diff`'s reading). */ -function objectsByName(side: PackageUpgradeSide | undefined): Map { - const out = new Map(); +/** The registry's default `priority` of an extension (the `objectExtensions` loop of `registerApp`). */ +const DEFAULT_EXTENSION_PRIORITY = 200; + +/** One side's objects as the registry serves them from that side. */ +interface SideObjects { + /** Every object the side reaches, owned or extended, by name, its fields merged. */ + byName: Map; + /** The names the side OWNS (declares in `objects`): the only ones listed as added or removed. */ + owned: Set; +} + +/** + * Objects by name, the LAST declaration of a name winning (`os diff`'s + * reading), each with the side's extensions merged over its fields (see the + * module header, *Extension fields count like owned ones*). + */ +function objectsByName(side: PackageUpgradeSide | undefined): SideObjects { + const byName = new Map(); for (const item of side?.objects ?? []) { - if (isBag(item) && typeof item.name === 'string' && item.name !== '') out.set(item.name, item); + if (isBag(item) && typeof item.name === 'string' && item.name !== '') byName.set(item.name, item); } - return out; + const owned = new Set(byName.keys()); + const extensions = (side?.objectExtensions ?? []) + .filter((ext): ext is Bag => isBag(ext) && typeof ext.extend === 'string' && ext.extend !== '' && isBag(ext.fields)) + .map((ext, order) => ({ ext, order, priority: typeof ext.priority === 'number' ? ext.priority : DEFAULT_EXTENSION_PRIORITY })) + .sort((a, b) => a.priority - b.priority || a.order - b.order); + for (const { ext } of extensions) { + const target = ext.extend as string; + const base = byName.get(target) ?? { name: target, fields: {} }; + byName.set(target, { ...base, fields: { ...(isBag(base.fields) ? base.fields : {}), ...(ext.fields as Bag) } }); + } + return { byName, owned }; } function fieldsOf(object: Bag | undefined): Map { @@ -302,8 +356,8 @@ function compareSeeds(installed: PackageUpgradeSide | undefined, incoming: Packa * version's order, objects one after another. */ export function comparePackageVersions(installed: PackageUpgradeSide | undefined, incoming: PackageUpgradeSide | undefined): PackageUpgradePlan { - const before = objectsByName(installed); - const after = objectsByName(incoming); + const { byName: before, owned: ownedBefore } = objectsByName(installed); + const { byName: after, owned: ownedAfter } = objectsByName(incoming); const plan: PackageUpgradePlan = { objects: { added: [], removed: [] }, fields: { added: [], removed: [] }, @@ -313,12 +367,21 @@ export function comparePackageVersions(installed: PackageUpgradeSide | undefined seeds: compareSeeds(installed, incoming), }; - for (const name of before.keys()) if (!after.has(name)) plan.objects.removed.push(name); - for (const name of after.keys()) if (!before.has(name)) plan.objects.added.push(name); - - for (const [object, beforeObject] of before) { - const afterObject = after.get(object); - if (!afterObject) continue; + // Owned objects only: an object a side only extends is neither created nor + // dropped by this upgrade. + for (const name of ownedBefore) if (!ownedAfter.has(name)) plan.objects.removed.push(name); + for (const name of ownedAfter) if (!ownedBefore.has(name)) plan.objects.added.push(name); + + // An object one side reaches only through extensions and the other does not + // reach at all is compared with no fields on that other side: the + // extensions' fields are what the upgrade adds or leaves behind. An OWNED + // object one side lacks is an added or removed object, listed above. + const unreached = (object: string): Bag => ({ name: object, fields: {} }); + const names = [...before.keys(), ...[...after.keys()].filter((name) => !before.has(name))]; + for (const object of names) { + const beforeObject = before.get(object) ?? (ownedAfter.has(object) ? undefined : unreached(object)); + const afterObject = after.get(object) ?? (ownedBefore.has(object) ? undefined : unreached(object)); + if (!beforeObject || !afterObject) continue; const beforeFields = fieldsOf(beforeObject); const afterFields = fieldsOf(afterObject); diff --git a/packages/objectql/src/package-upgrade-environment.test.ts b/packages/objectql/src/package-upgrade-environment.test.ts index 0399762197c..f2c56a7e98a 100644 --- a/packages/objectql/src/package-upgrade-environment.test.ts +++ b/packages/objectql/src/package-upgrade-environment.test.ts @@ -339,3 +339,65 @@ describe("the `manifest` service's planUpgrade reads the protocol's served overr } }); }); + +describe('objectExtensions: an extension field is planned and its column read like an owned one (#34095)', () => { + // HotCRM 6.2.0 → 6.4.0's shape: the core package owns `crm_account`, the + // o2c package of the same artifact adds its receivables figures through + // `objectExtensions`. + const SUMMARY = { type: 'summary', summaryOperations: { object: 'crm_invoice', field: 'amount', function: 'sum' } }; + const artifact = (extensionFields?: Record) => ({ + packages: [ + { manifest: { id: 'com.acme.crm', name: 'crm', version: '1.0.0', type: 'app', objects: [{ name: 'crm_account', fields: { name: { type: 'text' } } }] } }, + { + manifest: { + id: 'com.acme.o2c', name: 'o2c', version: '1.0.0', type: 'app', + ...(extensionFields ? { objectExtensions: [{ extend: 'crm_account', fields: extensionFields }] } : {}), + }, + }, + ], + }); + + async function withPlanUpgrade(rows: Row[], served: Record, run: (planUpgrade: (a: unknown, b: unknown) => ReturnType) => Promise) { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + try { + const ql = kernel.getService('objectql'); + ql.registerDriver(makeDriver({ crm_account: rows }) as any, true); + (ql.registry as any).registerObject({ name: 'crm_account', fields: served }); + const manifest = kernel.getService<{ planUpgrade(a: unknown, b: unknown): ReturnType }>('manifest'); + await run((a, b) => manifest.planUpgrade(a, b)); + } finally { + await kernel.shutdown(); + } + } + + it('the upgrade that adds extension fields lists them in fields.added', async () => { + await withPlanUpgrade([{ id: 'a1', name: 'Acme' }], { name: { type: 'text' } }, async (planUpgrade) => { + const { plan, environment } = await planUpgrade(artifact(), artifact({ invoiced_amount: SUMMARY, received_amount: SUMMARY })); + expect(plan.fields.added.map((f) => `${f.object}.${f.field}`)).toEqual(['crm_account.invoiced_amount', 'crm_account.received_amount']); + expect(plan.objects).toEqual({ added: [], removed: [] }); + expect(environment.columns).toEqual([]); + }); + }); + + it('the rollback lists them in fields.removed and counts the rows holding a value', async () => { + const served = { name: { type: 'text' }, invoiced_amount: { type: 'number' } }; + const rows = [{ id: 'a1', name: 'Acme', invoiced_amount: 120 }, { id: 'a2', name: 'Globex', invoiced_amount: null }]; + await withPlanUpgrade(rows, served, async (planUpgrade) => { + const { plan, environment } = await planUpgrade(artifact({ invoiced_amount: SUMMARY }), artifact()); + expect(plan.fields.removed.map((f) => `${f.object}.${f.field}`)).toEqual(['crm_account.invoiced_amount']); + expect(environment.columns).toEqual([{ object: 'crm_account', field: 'invoiced_amount', reasons: ['removed'], rows: 1 }]); + }); + }); + + it('a retyped extension field is a type change whose column is read', async () => { + const served = { name: { type: 'text' }, tier: { type: 'text' } }; + const rows = [{ id: 'a1', name: 'Acme', tier: 'gold' }, { id: 'a2', name: 'Globex', tier: 'silver' }]; + await withPlanUpgrade(rows, served, async (planUpgrade) => { + const { plan, environment } = await planUpgrade(artifact({ tier: { type: 'text' } }), artifact({ tier: { type: 'number' } })); + expect(plan.typeChanges).toEqual([{ object: 'crm_account', field: 'tier', from: 'text', to: 'number', category: 'needs_confirm' }]); + expect(environment.columns).toEqual([{ object: 'crm_account', field: 'tier', reasons: ['type_change'], rows: 2 }]); + }); + }); +}); diff --git a/packages/objectql/src/package-upgrade-environment.ts b/packages/objectql/src/package-upgrade-environment.ts index c4f755ef384..5a9cccc73e8 100644 --- a/packages/objectql/src/package-upgrade-environment.ts +++ b/packages/objectql/src/package-upgrade-environment.ts @@ -201,9 +201,19 @@ const REFERENCE_TYPES: ReadonlySet = new Set(['lookup', 'master_detail', type Bag = Record; const isBag = (value: unknown): value is Bag => typeof value === 'object' && value !== null && !Array.isArray(value); -/** One side as the comparison reads it: a multi-package artifact folded by the platform's one reader. */ +/** + * One side as the comparison reads it: a multi-package artifact folded by the + * platform's one reader. `objectExtensions` is read with `objects` (#34095): + * the comparison merges each extension's fields onto its target, so a field an + * extension adds, retypes or drops is planned, counted and judged like an + * owned one. + */ function sideOf(artifact: unknown): PackageUpgradeSide { - return { objects: resolveStackCollection(artifact, 'objects'), data: resolveStackCollection(artifact, 'data') }; + return { + objects: resolveStackCollection(artifact, 'objects'), + objectExtensions: resolveStackCollection(artifact, 'objectExtensions'), + data: resolveStackCollection(artifact, 'data'), + }; } /**