From e6e8ff056bb6ccc14ebb76c21b25a986a2f71772 Mon Sep 17 00:00:00 2001 From: sonika-shah <58761340+sonika-shah@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:36:06 +0530 Subject: [PATCH 1/2] Fixes #39764: make relationship types from a 2.0 upgrade valid in 2.1 (#39765) * Create a relationship type for a free-text inverse during the 2.1 upgrade In 2.0 a glossary term relation type's inverse was free text, and a link saved from the inverse end was stored under that text. The 2.1.0 data migration requires every inverse to name a configured type and throws otherwise, which halts the upgrade. Before mapping, the migration now points each unmatched inverse at the type it names in another case or by display name, or adds a type for it, and renames the term links stored under the old text (dropping a row that already exists under the new name). Links are renamed before the settings are written, so an interrupted run repeats the repair. * Repair relationship types the 2.1 upgrade stored without 2.1 validation - The 2.1.0 conversion runs only when relationship_type_entity is empty and only inserts, so a re-run keeps what 2.1 changed since. - A symmetric type's free-text inverse resolves to the type itself. - A name with a space gets an encoded default predicate; a dotted name is stored under its quoted FQN and hash, and lookups by name quote it. - New 2.1.2 step RelationshipTypeRepair for clusters already upgraded: every type can be saved again, each holds its own predicate (seed predicates stay free for their seeds), term links stored under no type point at one, and links get the type id and json 2.1 reads. * Keep one relation type per name and quote names in type lookups - The 2.1.0 conversion keeps one definition per name from the 2.0 settings (the system-defined one, else the first) instead of failing the insert on the second copy. - The settings synchronizer and PUT /relationshipTypes look a type up under its quoted FQN, so a name holding a dot updates the stored type instead of colliding with it. - Decision records note the search and RDF reindex after the repair and the deprecated settings endpoints as a known gap. * Match relation types by name only when resolving upgraded inverses and link texts 2.0 resolved an inverse and a stored link type by name, ignoring case, never by display name. Matching a display name pointed a type at another type's inverse and left a one-way pair, so links saved from the higher term id read back as the partner's inverse. Text equal only to another type's display name now gets its own type; texts naming the same missing type still share one. * Pair a relationship type left without its inverse in the 2.1.2 repair A stock 2.1.0 upgrade kept the last definition of a name 2.0 defined twice, so a type can have no inverse while its partner names it, and a link authored from the higher term reads as the partner's inverse on both terms. The repair now gives such a type the one live type naming it, unless a link stored under it was authored on 2.1 from the higher term: a pair would read that link the other way round, so the type is left and logged. * Revert "Pair a relationship type left without its inverse in the 2.1.2 repair" This reverts commit 6874b998f7e. From the stored types alone, a type a duplicate name left without its inverse looks the same as a 2.0 type that never had one, and pairing the latter reverses links 2.0 stored from the higher term. The cosmetic gap it closed is recorded in the decision record instead. (cherry picked from commit 80ea0f217497b530e8c27ed4a24faa3cb77031cd) --- ...-repairs-relationship-types-2-1-rejects.md | 71 ++ ...lation-inverses-into-relationship-types.md | 66 ++ .../it/bootstrap/TestSuiteBootstrap.java | 2 +- .../it/tests/RelationshipTypeResourceIT.java | 12 + .../migration/ScratchDatabasePerTest.java | 91 +++ .../OntologyInverseRepairMigrationIT.java | 375 ++++++++++ .../RelationshipTypeRepairMigrationIT.java | 365 ++++++++++ .../openmetadata/it/util/ScratchDatabase.java | 68 ++ .../migration/mysql/v212/Migration.java | 8 + .../migration/postgres/v212/Migration.java | 8 + .../utils/v210/OntologyMigration.java | 392 ++++++++++- .../utils/v212/RelationshipTypeRepair.java | 657 ++++++++++++++++++ .../LegacyRelationshipTypeMapper.java | 10 +- .../LegacyRelationshipTypeSynchronizer.java | 7 +- .../ontology/RelationshipTypeResolver.java | 6 +- .../ontology/RelationshipTypeResource.java | 4 +- .../utils/v210/OntologyMigrationTest.java | 231 ++++++ .../v212/RelationshipTypeRepairTest.java | 235 +++++++ .../LegacyRelationshipTypeMapperTest.java | 19 + ...egacyRelationshipTypeSynchronizerTest.java | 11 + .../RelationshipTypeResolverTest.java | 9 + 21 files changed, 2624 insertions(+), 23 deletions(-) create mode 100644 docs/decisions/2026-12-04-upgrade-repairs-relationship-types-2-1-rejects.md create mode 100644 docs/decisions/2026-12-04-upgrade-turns-free-text-relation-inverses-into-relationship-types.md create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/ScratchDatabasePerTest.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v210/OntologyInverseRepairMigrationIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v212/RelationshipTypeRepairMigrationIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ScratchDatabase.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepair.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepairTest.java diff --git a/docs/decisions/2026-12-04-upgrade-repairs-relationship-types-2-1-rejects.md b/docs/decisions/2026-12-04-upgrade-repairs-relationship-types-2-1-rejects.md new file mode 100644 index 000000000000..8c0f75a592e2 --- /dev/null +++ b/docs/decisions/2026-12-04-upgrade-repairs-relationship-types-2-1-rejects.md @@ -0,0 +1,71 @@ +# The 2.1.2 upgrade repairs relationship types a 2.1 save rejects + +- **Status:** Accepted +- **Revisions:** v1 2026-12-04 (initial) +- **Deciders:** OpenMetadata maintainers +- **Guard:** RelationshipTypeRepairTest; RelationshipTypeRepairMigrationIT; RelationshipTypeResolverTest#requireLooksUpADottedNameAsOneQuotedSegment; LegacyRelationshipTypeSynchronizerTest#upsertFindsADottedNameUnderItsQuotedFqn; RelationshipTypeResourceIT#putUpdatesATypeWhoseNameHoldsADotInPlace +- **Related:** ADR:2026-12-04-upgrade-turns-free-text-relation-inverses-into-relationship-types; ADR:2026-11-11-a-data-migration-carries-its-own-logic + +## Context + +The released 2.1.0 data migration stored every 2.0 relation type as a `RelationshipType` without +the checks a 2.1 write runs (`RelationshipTypeValidator` and the unique predicate check). 2.0 +accepted shapes 2.1 rejects, so after an upgrade that succeeded: + +- saving such a type with no change fails: a symmetric type naming another type as its inverse, a + relative predicate, an incompatible characteristic pair, an asymmetric type that is its own + inverse, a functional type with no limit of one; +- two types share a predicate, so whichever is saved second fails, and a seed type whose predicate + a custom type holds is never created (each start logs "already governed by"); +- glossary term links stored under a text that names no type (the inverse text of a type deleted + in 2.0) fail to read: the term page, the relations graph, search, PATCH and CSV export all error; +- links 2.1.0 could not resolve never got the type id and json fields 2.1 reads; +- a name holding a dot was stored under a hash no lookup computes. + +Clusters already at 2.1.0 or 2.1.1 do not run the corrected 2.1.0 migration again, so the repair +is a 2.1.2 step, run once. + +## Decision + +In one transaction, each stored type is changed only as far as a 2.1 save requires: + +1. The FQN is the quoted name and `fqnHash` its `buildHash`. +2. Both characteristics of an incompatible pair (symmetric/asymmetric, reflexive/irreflexive, + asymmetric/reflexive) are cleared; a functional type gets `sourceMax` 1 and an inverse + functional one `targetMax` 1; a symmetric type becomes its own inverse; an asymmetric type that + is its own inverse loses asymmetric. Inverse references are refreshed to their target's name. +3. Every type ends with an absolute predicate no other type holds. A seed type's predicate is + reserved for that seed. Otherwise one holder keeps a predicate: live before deleted, system + before custom, the type whose own default it is, then by name. Every other holder, and any type + with a relative predicate, gets its default predicate with a numeric suffix until free; its IRI + follows when it was unset or equal to the old predicate. +4. Each stored link text that names no type exactly moves to a live type named by it ignoring + case, else to a new associative type whose display name is the text; texts that differ only in + case share it. A display name is never matched, as 2.0 resolved link types by name only. A + blank text moves to `relatedTo`. +5. Every glossary term link's type id and json fields are set from its column, as 2.1.0 did for + the links it resolved. + +The step works on rows and JSON trees, as every step after 2.1.0 does: the seed predicates it +reserves, a created type's shape and id, and the default predicate are its own constants, frozen +at the 2.1.2 seeds and formats. A type the repair does not need is not written, and a second run +changes nothing. Every runtime lookup of a type by name (the resolver, the settings synchronizer, +PUT `/relationshipTypes`) quotes the name, as the stored FQN is quoted. + +## Consequences + +Every upgraded type can be saved again, the seed types are created on the next start, and every +link reads under a stored type. Changes are logged per type. When the log reports changed +predicates or moved links, reindex the RDF store and the glossary term search index: search +documents carry each term's related terms with their relation type and are not rewritten here. + +Left alone on purpose: names that differ only in case (2.1 allows them) and links of a +soft-deleted type, which 2.1 refuses until the type is restored. A cluster already on 2.1 whose 2.0 +settings defined a name twice keeps the last definition, which can lack the inverse its partner +names, so a link saved from the higher term shows one label on both terms. It is not re-paired: +from the stored types a 2.0 type that never had an inverse looks the same, and pairing it would +reverse the links 2.0 stored from the higher term. A link 2.0 stored under another +type, as a symmetric type's inverse, keeps reading as that type: 2.0 kept no trace of the type it +was saved under. The deprecated `/system/settings` relation type endpoints still read the 2.0 +settings row, which this step does not rewrite; a write through them maps that row again. The UI +no longer calls them. diff --git a/docs/decisions/2026-12-04-upgrade-turns-free-text-relation-inverses-into-relationship-types.md b/docs/decisions/2026-12-04-upgrade-turns-free-text-relation-inverses-into-relationship-types.md new file mode 100644 index 000000000000..6ad725df27f0 --- /dev/null +++ b/docs/decisions/2026-12-04-upgrade-turns-free-text-relation-inverses-into-relationship-types.md @@ -0,0 +1,66 @@ +# The 2.1 upgrade turns a free-text relation inverse into a relationship type + +- **Status:** Accepted +- **Revisions:** v1 2026-12-04 (initial) +- **Deciders:** OpenMetadata maintainers +- **Guard:** OntologyMigrationTest#createsTheInverseTypeAFreeTextInverseNamed; OntologyMigrationTest#resolvesAnInverseThatNamesAnExistingTypeInAnotherCase; OntologyMigrationTest#anInverseMatchingOnlyAnotherTypesDisplayNameGetsItsOwnType; OntologyMigrationTest#generatedNameNeverCollidesWithAnExistingType; OntologyMigrationTest#aSymmetricTypesFreeTextInverseIsTheTypeItself; OntologyMigrationTest#aNameDefinedTwiceKeepsTheSystemDefinitionElseTheFirst; LegacyRelationshipTypeMapperTest#aNameWithASpaceGetsAnEncodedDefaultPredicate; LegacyRelationshipTypeMapperTest#aDottedNameIsStoredUnderTheQuotedFqnItIsLookedUpBy; OntologyInverseRepairMigrationIT +- **Related:** ADR:2026-11-19-relationship-type-references-carry-their-name; ADR:2026-12-04-upgrade-repairs-relationship-types-2-1-rejects + +## Context + +In 2.0 a glossary term relation type's `inverseRelation` was free text: the settings form did not +check it against the configured types. A link saved from the inverse end was stored with that text +as its `relationType`, because the canonical row is keyed by the smaller term id and takes the +inverse name when the link points the other way. + +2.1 turns each configured type into a `RelationshipType` entity, and both the inverse reference +and every stored link must name one. An inverse that names no type made the 2.1.0 data migration +throw, which halted the upgrade, and the links stored under that text could not be read in 2.1 +even if the migration got past it. + +Dropping the inverse is not enough: the links stored under the text would still name no type. +Rewriting those links onto the base type in reverse would change rows the user saved without +saying so, and would discard the inverse label they chose. + +## Decision + +Before mapping the settings, the 2.1.0 data migration keeps one definition per name, since each +name becomes one stored type: the system-defined one, else the first. The others are dropped from +the settings row and logged. It then resolves every inverse that does not match a configured type +name exactly: + +1. A blank inverse is removed. +2. A symmetric type's inverse points at the type itself, since a symmetric relation is its own + inverse; links stored under the text are renamed to the type. +3. An inverse that matches a configured type's name ignoring case points at that type. A display + name is never matched: 2.0 resolved an inverse by name only, so text equal to another type's + label (for example "Controlled By" on `regulates`, while `controlledBy` is the inverse of + `controls`) was never that type, and reusing it would leave a one-way pair. +4. Otherwise a type is added to the settings for it: the display name is the inverse text; the + name is that text in camelCase or, when that is not a valid name, `inverseOf`; a + numeric suffix makes it unique ignoring case, and it is capped at 60 characters, below the + 64-character `relationType` column. It names the base type as its inverse, keeps the + base type's category and symmetric flags, and mirrors the directional ones (`sourceMax` and + `targetMax`, functional and inverse functional, domain and range, one-to-many and many-to-one). + Types that name the same missing inverse, ignoring case, share one added type. + +Glossary term links stored under the old inverse text are renamed to the resolved name, in the +column and in `json.relationType`. Where the same pair already has a row under that name, the old +row is deleted instead. Links are renamed before the settings are written back, so an interrupted +run repeats the whole repair. A second run finds nothing to repair. On MySQL the stored text is +matched byte for byte, so a case-insensitive collation cannot merge two texts that differ in case. + +The conversion into `relationship_type_entity` runs in one transaction and only when that table is +empty, and it only inserts. A changed 2.1.0 migration runs again on a cluster still at 2.1.0, and +by then the table holds the types as 2.1 edited, deleted or hard-deleted them; overwriting them +from the 2.0 settings would undo that. Each row's FQN is the quoted name and its `fqnHash` is +`FullyQualifiedName.buildHash` of it, the hash a lookup by name computes, so a name holding a dot +is one segment. A type with no predicate gets the default one with the name URL-encoded, so a name +holding a space yields a valid URI. + +## Consequences + +Upgrades from 2.0 no longer stop on an unmatched inverse, and every link saved in 2.0 is readable +in 2.1 under a type the administrator can see, rename or edit. The added types are not system +defined. The repair runs only inside the 2.1.0 data migration: settings saved later go through +the 2.1 relationship type API, which already requires an inverse to name a type. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/bootstrap/TestSuiteBootstrap.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/bootstrap/TestSuiteBootstrap.java index cc84bdbd0b03..e9011f949a9d 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/bootstrap/TestSuiteBootstrap.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/bootstrap/TestSuiteBootstrap.java @@ -637,7 +637,7 @@ public static GenericContainer getFusekiContainer() { } /** The isolated metadata database, for scale resource sampling. */ - public static GenericContainer getDatabaseContainer() { + public static JdbcDatabaseContainer getDatabaseContainer() { return DATABASE_CONTAINER; } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RelationshipTypeResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RelationshipTypeResourceIT.java index f55fa413c666..134b651a4af9 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RelationshipTypeResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RelationshipTypeResourceIT.java @@ -20,6 +20,7 @@ import java.nio.charset.StandardCharsets; import java.util.Set; import java.util.UUID; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.openmetadata.it.util.SdkClients; @@ -78,6 +79,17 @@ private static CreateRelationshipType request(String name) { .withPaletteKey(RelationshipPaletteKey.VIOLET); } + @Test + void putUpdatesATypeWhoseNameHoldsADotInPlace(final TestNamespace ns) { + final CreateRelationshipType request = request(ns.prefix("part.of")); + final RelationshipType created = service().upsert(request); + + final RelationshipType updated = service().upsert(request.withDescription("Updated by PUT")); + + assertEquals(created.getId(), updated.getId()); + assertEquals("Updated by PUT", updated.getDescription()); + } + @Override protected RelationshipType createEntity(CreateRelationshipType request) { return service().create(request); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/ScratchDatabasePerTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/ScratchDatabasePerTest.java new file mode 100644 index 000000000000..70e9d2728085 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/ScratchDatabasePerTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests.migration; + +import java.lang.reflect.Method; +import java.util.stream.Stream; +import org.jdbi.v3.core.Jdbi; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; +import org.openmetadata.it.util.ScratchDatabase; +import org.openmetadata.service.jdbi3.locator.ConnectionType; + +/** + * Runs each test method against its own empty {@link ScratchDatabase}, dropped when the method + * returns, so SQL and migration tests that build their own schema neither share one nor outlive it. + * A test reads its database through {@link #jdbi()}, or receives it before the method runs when the + * test class implements {@link Target}. + */ +public final class ScratchDatabasePerTest implements InvocationInterceptor { + private static final ThreadLocal CURRENT = new ThreadLocal<>(); + + /** A test class that prepares its schema before each method, where a {@code @BeforeEach} cannot. */ + public interface Target { + void useScratchDatabase(Jdbi jdbi); + } + + public static Jdbi jdbi() { + Jdbi jdbi = CURRENT.get(); + if (jdbi == null) { + throw new IllegalStateException( + "No scratch database: add @ExtendWith(ScratchDatabasePerTest)"); + } + return jdbi; + } + + /** The dialect names a test parameterized over dialects runs: only the lane's. */ + public static Stream laneDialect() { + return Stream.of(ScratchDatabase.dialect() == ConnectionType.MYSQL ? "mysql" : "postgres"); + } + + @Override + public void interceptTestMethod( + Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) + throws Throwable { + runOnScratchDatabase(invocation, extensionContext); + } + + @Override + public void interceptTestTemplateMethod( + Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) + throws Throwable { + runOnScratchDatabase(invocation, extensionContext); + } + + private static void runOnScratchDatabase( + Invocation invocation, ExtensionContext extensionContext) throws Throwable { + Throwable[] failure = new Throwable[1]; + ScratchDatabase.withJdbi( + jdbi -> { + CURRENT.set(jdbi); + try { + if (extensionContext.getRequiredTestInstance() instanceof Target target) { + target.useScratchDatabase(jdbi); + } + invocation.proceed(); + } catch (Throwable t) { + failure[0] = t; + } finally { + CURRENT.remove(); + } + }); + if (failure[0] != null) { + throw failure[0]; + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v210/OntologyInverseRepairMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v210/OntologyInverseRepairMigrationIT.java new file mode 100644 index 000000000000..1ee0a84bb5e0 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v210/OntologyInverseRepairMigrationIT.java @@ -0,0 +1,375 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests.migration.v210; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.UUID; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.tests.migration.ScratchDatabasePerTest; +import org.openmetadata.it.util.ScratchDatabase; +import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; +import org.openmetadata.schema.configuration.GlossaryTermRelationType; +import org.openmetadata.schema.configuration.RelationCategory; +import org.openmetadata.schema.entity.data.RelationshipType; +import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.v210.OntologyMigration; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * Runs the 2.1.0 relationship type migration against real MySQL and PostgreSQL for a 2.0 setting + * whose inverse is free text that names no relation type. 2.0 stored a link saved from the + * inverse end under that text, so the migration must create the inverse type and move those links + * onto it, or 2.1 cannot read them. + */ +@ExtendWith(ScratchDatabasePerTest.class) +class OntologyInverseRepairMigrationIT implements ScratchDatabasePerTest.Target { + private static final String SETTING = "glossaryTermRelationSettings"; + private static final String GLOSSARY_TERM = "glossaryTerm"; + private static final String TABLE = "table"; + private static final int RELATED_TO = Relationship.RELATED_TO.ordinal(); + private static final String BASE = "dependsOn"; + private static final String FREE_TEXT_INVERSE = "Dependency Of"; + private static final String CREATED_INVERSE = "dependencyOf"; + + private final UUID a = UUID.randomUUID(); + private final UUID b = UUID.randomUUID(); + private final UUID c = UUID.randomUUID(); + + @Override + public void useScratchDatabase(final Jdbi jdbi) { + final boolean mysql = ScratchDatabase.dialect() == ConnectionType.MYSQL; + jdbi.useHandle(handle -> (mysql ? MYSQL_TABLES : POSTGRES_TABLES).forEach(handle::execute)); + } + + @Test + void linksStoredUnderAFreeTextInverseMoveOntoTheCreatedType() { + ScratchDatabasePerTest.jdbi() + .useHandle( + handle -> { + seedSettings(handle); + insertLink(handle, a, b, GLOSSARY_TERM, BASE); + insertLink(handle, b, c, GLOSSARY_TERM, FREE_TEXT_INVERSE); + insertLink(handle, a, c, GLOSSARY_TERM, FREE_TEXT_INVERSE); + insertLink(handle, a, c, GLOSSARY_TERM, CREATED_INVERSE); + insertLink(handle, a, b, TABLE, FREE_TEXT_INVERSE); + + migrate(handle); + + assertEquals( + Map.of( + a + ">" + b + ":" + GLOSSARY_TERM, BASE, + b + ">" + c + ":" + GLOSSARY_TERM, CREATED_INVERSE, + a + ">" + c + ":" + GLOSSARY_TERM, CREATED_INVERSE, + a + ">" + b + ":" + TABLE, FREE_TEXT_INVERSE), + links(handle), + "a link already stored under the created type is kept once; other entities" + + " are never touched"); + assertEquals( + CREATED_INVERSE, + jsonRelationType(handle, b, c), + "the json discriminator moves with the column"); + assertEquals( + CREATED_INVERSE, typeNamed(storedSettings(handle), BASE).getInverseRelation()); + assertEquals(BASE, relationshipType(handle, CREATED_INVERSE).getInverse().getName()); + assertEquals(CREATED_INVERSE, relationshipType(handle, BASE).getInverse().getName()); + }); + } + + @Test + void aSecondRunKeepsWhat21ChangedSinceTheFirst() { + ScratchDatabasePerTest.jdbi() + .useHandle( + handle -> { + seedSettings(handle); + insertLink(handle, b, c, GLOSSARY_TERM, FREE_TEXT_INVERSE); + migrate(handle); + final Map linksAfterFirstRun = links(handle); + final String settingsAfterFirstRun = settingsJson(handle); + saveType(handle, relationshipType(handle, BASE).withDescription("Edited in 2.1")); + saveType(handle, relationshipType(handle, "narrower").withDeleted(true)); + handle.execute("DELETE FROM relationship_type_entity WHERE name = 'broader'"); + + migrate(handle); + + assertEquals("Edited in 2.1", relationshipType(handle, BASE).getDescription()); + assertTrue(relationshipType(handle, "narrower").getDeleted(), "stays deleted"); + assertEquals(0, relationshipTypeCount(handle, "broader"), "is not inserted again"); + assertEquals(linksAfterFirstRun, links(handle)); + assertEquals(settingsAfterFirstRun, settingsJson(handle)); + }); + } + + @Test + void aNameDefinedTwiceConvertsToOneType() { + ScratchDatabasePerTest.jdbi() + .useHandle( + handle -> { + seedSettings( + handle, + List.of( + relationType("owns", "Owns", null), + relationType("owns", "Owns Again", null))); + + migrate(handle); + + assertEquals(1, relationshipTypeCount(handle, "owns")); + }); + } + + @Test + void namesWithASpaceOrADotConvertUnderTheHashTheirLookupComputes() { + ScratchDatabasePerTest.jdbi() + .useHandle( + handle -> { + seedSettings( + handle, + List.of( + relationType("held by", "Held By", null), + relationType("part.of", "Part Of", null))); + + migrate(handle); + + for (final String name : List.of("held by", "part.of")) { + assertEquals( + FullyQualifiedName.buildHash(FullyQualifiedName.quoteName(name)), + fqnHash(handle, name), + name); + } + }); + } + + private static void migrate(final Handle handle) { + OntologyMigration.migrateRelationshipTypes(handle, ScratchDatabase.dialect()); + } + + private static void seedSettings(final Handle handle) { + seedSettings( + handle, + List.of( + relationType(BASE, "Depends On", FREE_TEXT_INVERSE), + relationType("broader", "Broader", "narrower"), + relationType("narrower", "Narrower", "broader"))); + } + + private static void seedSettings( + final Handle handle, final List relationTypes) { + final GlossaryTermRelationSettings settings = + new GlossaryTermRelationSettings().withRelationTypes(relationTypes); + handle + .createUpdate( + "INSERT INTO openmetadata_settings (configType, json) VALUES (:configType, " + + jsonValue() + + ")") + .bind("configType", SETTING) + .bind("json", JsonUtils.pojoToJson(settings)) + .execute(); + } + + private static GlossaryTermRelationType relationType( + final String name, final String displayName, final String inverse) { + return new GlossaryTermRelationType() + .withName(name) + .withDisplayName(displayName) + .withDescription(displayName) + .withInverseRelation(inverse) + .withCategory(RelationCategory.ASSOCIATIVE) + .withIsCrossGlossaryAllowed(true) + .withIsSystemDefined(false); + } + + private static void insertLink( + final Handle handle, + final UUID from, + final UUID to, + final String entity, + final String relationType) { + handle + .createUpdate( + "INSERT INTO entity_relationship" + + " (fromId, toId, fromEntity, toEntity, relation, relationType, json)" + + " VALUES (:fromId, :toId, :entity, :entity, :relation, :relationType, " + + jsonValue() + + ")") + .bind("fromId", from.toString()) + .bind("toId", to.toString()) + .bind("entity", entity) + .bind("relation", RELATED_TO) + .bind("relationType", relationType) + .bind("json", JsonUtils.pojoToJson(Map.of("relationType", relationType))) + .execute(); + } + + private static Map links(final Handle handle) { + final Map links = new TreeMap<>(); + handle + .createQuery("SELECT fromId, toId, fromEntity, relationType FROM entity_relationship") + .map( + (row, context) -> + Map.entry( + row.getString("fromId") + + ">" + + row.getString("toId") + + ":" + + row.getString("fromEntity"), + row.getString("relationType"))) + .forEach(link -> links.merge(link.getKey(), link.getValue(), (x, y) -> x + "," + y)); + return links; + } + + private static String jsonRelationType(final Handle handle, final UUID from, final UUID to) { + return handle + .createQuery("SELECT json FROM entity_relationship WHERE fromId = :fromId AND toId = :toId") + .bind("fromId", from.toString()) + .bind("toId", to.toString()) + .mapTo(String.class) + .map(json -> JsonUtils.readTree(json).path("relationType").asText()) + .one(); + } + + private static String settingsJson(final Handle handle) { + return handle + .createQuery("SELECT json FROM openmetadata_settings WHERE configType = :configType") + .bind("configType", SETTING) + .mapTo(String.class) + .one(); + } + + private static GlossaryTermRelationSettings storedSettings(final Handle handle) { + return JsonUtils.readValue(settingsJson(handle), GlossaryTermRelationSettings.class); + } + + private static GlossaryTermRelationType typeNamed( + final GlossaryTermRelationSettings settings, final String name) { + return settings.getRelationTypes().stream() + .filter(type -> name.equals(type.getName())) + .findFirst() + .orElseThrow(); + } + + private static RelationshipType relationshipType(final Handle handle, final String name) { + return handle + .createQuery("SELECT json FROM relationship_type_entity WHERE name = :name") + .bind("name", name) + .mapTo(String.class) + .map(json -> JsonUtils.readValue(json, RelationshipType.class)) + .one(); + } + + private static int relationshipTypeCount(final Handle handle, final String name) { + return handle + .createQuery("SELECT COUNT(*) FROM relationship_type_entity WHERE name = :name") + .bind("name", name) + .mapTo(Integer.class) + .one(); + } + + private static String fqnHash(final Handle handle, final String name) { + return handle + .createQuery("SELECT fqnHash FROM relationship_type_entity WHERE name = :name") + .bind("name", name) + .mapTo(String.class) + .one(); + } + + /** Stands for a 2.1 write of the type, which keeps its row and replaces its json. */ + private static void saveType(final Handle handle, final RelationshipType type) { + handle + .createUpdate( + "UPDATE relationship_type_entity SET json = " + jsonValue() + " WHERE id = :id") + .bind("json", JsonUtils.pojoToJson(type)) + .bind("id", type.getId().toString()) + .execute(); + } + + private static String jsonValue() { + return ScratchDatabase.dialect() == ConnectionType.MYSQL ? ":json" : "CAST(:json AS jsonb)"; + } + + /** Column types as v001/v004, 1.13.0 (relationType + primary key) and 2.1.0 create them. */ + private static final List MYSQL_TABLES = + List.of( + """ + CREATE TABLE entity_relationship ( + fromId VARCHAR(36) NOT NULL, + toId VARCHAR(36) NOT NULL, + fromEntity VARCHAR(256) NOT NULL, + toEntity VARCHAR(256) NOT NULL, + relation TINYINT NOT NULL, + relationType VARCHAR(64) NOT NULL DEFAULT '', + json JSON, + deleted BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (fromId, toId, relation, relationType)) + """, + """ + CREATE TABLE openmetadata_settings ( + id MEDIUMINT NOT NULL AUTO_INCREMENT, + configType VARCHAR(36) NOT NULL, + json JSON NOT NULL, + PRIMARY KEY (id, configType), + UNIQUE (configType)) + """, + """ + CREATE TABLE relationship_type_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.id'))) STORED + NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.name'))) + STORED NOT NULL, + fqnHash VARCHAR(768) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + json JSON NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY relationship_type_fqn_hash_unique (fqnHash)) + """); + + private static final List POSTGRES_TABLES = + List.of( + """ + CREATE TABLE entity_relationship ( + fromId VARCHAR(36) NOT NULL, + toId VARCHAR(36) NOT NULL, + fromEntity VARCHAR(256) NOT NULL, + toEntity VARCHAR(256) NOT NULL, + relation SMALLINT NOT NULL, + relationType VARCHAR(64) NOT NULL DEFAULT '', + json JSONB, + deleted BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (fromId, toId, relation, relationType)) + """, + """ + CREATE TABLE openmetadata_settings ( + id SERIAL NOT NULL, + configType VARCHAR(36) NOT NULL, + json JSONB NOT NULL, + PRIMARY KEY (id, configType), + UNIQUE (configType)) + """, + """ + CREATE TABLE relationship_type_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json ->> 'name') STORED NOT NULL, + fqnHash VARCHAR(768) NOT NULL, + json JSONB NOT NULL, + PRIMARY KEY (id), + CONSTRAINT relationship_type_fqn_hash_unique UNIQUE (fqnHash)) + """); +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v212/RelationshipTypeRepairMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v212/RelationshipTypeRepairMigrationIT.java new file mode 100644 index 000000000000..636b49280800 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/migration/v212/RelationshipTypeRepairMigrationIT.java @@ -0,0 +1,365 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests.migration.v212; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.time.Clock; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import java.util.stream.Collectors; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.tests.migration.ScratchDatabasePerTest; +import org.openmetadata.it.util.ScratchDatabase; +import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; +import org.openmetadata.schema.configuration.GlossaryTermRelationType; +import org.openmetadata.schema.configuration.RelationCategory; +import org.openmetadata.schema.entity.data.RelationshipType; +import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.v212.RelationshipTypeRepair; +import org.openmetadata.service.ontology.LegacyRelationshipTypeMapper; +import org.openmetadata.service.ontology.RelationshipTypeValidator; +import org.openmetadata.service.util.EntityUtil; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * Runs the 2.1.2 relationship type repair against real MySQL and PostgreSQL over the rows the + * released 2.1.0 conversion stored: types a 2.1 save rejects, a dotted name under a hash no lookup + * computes, and term links whose stored type names no type. + */ +@ExtendWith(ScratchDatabasePerTest.class) +class RelationshipTypeRepairMigrationIT implements ScratchDatabasePerTest.Target { + private static final String GLOSSARY_TERM = "glossaryTerm"; + private static final String TABLE = "table"; + private static final int RELATED_TO = Relationship.RELATED_TO.ordinal(); + private static final String ORPHAN = "Holder Of"; + private static final String DOTTED = "part.of"; + + private final String t1 = UUID.randomUUID().toString(); + private final String t2 = UUID.randomUUID().toString(); + private final String t3 = UUID.randomUUID().toString(); + private final String t4 = UUID.randomUUID().toString(); + + @Override + public void useScratchDatabase(final Jdbi jdbi) { + final boolean mysql = ScratchDatabase.dialect() == ConnectionType.MYSQL; + jdbi.useHandle(handle -> (mysql ? MYSQL_TABLES : POSTGRES_TABLES).forEach(handle::execute)); + } + + @Test + void everyTypeCanBeSavedAndEveryTermLinkNamesAStoredType() { + ScratchDatabasePerTest.jdbi() + .useHandle( + handle -> { + storeAs210(handle); + link(handle, t1, t2, GLOSSARY_TERM, "controls", typeId(handle, "controls")); + link(handle, t2, t3, GLOSSARY_TERM, ORPHAN, null); + link(handle, t3, t4, GLOSSARY_TERM, DOTTED, typeId(handle, DOTTED)); + link(handle, t1, t4, GLOSSARY_TERM, "", null); + link(handle, t1, t4, GLOSSARY_TERM, "relatedTo", typeId(handle, "relatedTo")); + link(handle, t4, t1, TABLE, ORPHAN, null); + + repair(handle); + + types(handle).forEach(RelationshipTypeValidator::validate); + final List predicates = + types(handle).stream().map(RelationshipType::getRdfPredicate).toList(); + assertEquals(predicates.size(), Set.copyOf(predicates).size()); + assertEquals( + FullyQualifiedName.buildHash(FullyQualifiedName.quoteName(DOTTED)), + fqnHash(handle, DOTTED)); + assertEquals( + Map.of( + t1 + ">" + t2 + ":" + GLOSSARY_TERM, "controls", + t2 + ">" + t3 + ":" + GLOSSARY_TERM, "holderOf", + t3 + ">" + t4 + ":" + GLOSSARY_TERM, DOTTED, + t1 + ">" + t4 + ":" + GLOSSARY_TERM, "relatedTo", + t4 + ">" + t1 + ":" + TABLE, ORPHAN), + links(handle), + "a blank link already stored as relatedTo is kept once; other entities are" + + " never touched"); + assertEquals(ORPHAN, typeNamed(handle, "holderOf").getDisplayName()); + assertTrue(termLinksNameTheirType(handle)); + }); + } + + @Test + void aSecondRunChangesNothing() { + ScratchDatabasePerTest.jdbi() + .useHandle( + handle -> { + storeAs210(handle); + link(handle, t2, t3, GLOSSARY_TERM, ORPHAN, null); + repair(handle); + final Map typesAfterFirstRun = typeJson(handle); + final Map linksAfterFirstRun = linkJson(handle); + + repair(handle); + + assertEquals(typesAfterFirstRun, typeJson(handle)); + assertEquals(linksAfterFirstRun, linkJson(handle)); + }); + } + + private static void repair(final Handle handle) { + RelationshipTypeRepair.repair(handle, ScratchDatabase.dialect()); + } + + /** The rows the released 2.1.0 conversion stored for shapes 2.0 accepted. */ + private static void storeAs210(final Handle handle) { + final List types = + new LegacyRelationshipTypeMapper(Clock.systemUTC()) + .map( + new GlossaryTermRelationSettings() + .withRelationTypes( + List.of( + relationType("relatedTo") + .withIsSymmetric(true) + .withIsSystemDefined(true), + relationType("controls").withInverseRelation("controlledBy"), + relationType("controlledBy").withInverseRelation("controls"), + relationType("peerOf") + .withIsSymmetric(true) + .withInverseRelation("relatedTo"), + relationType("dependsOnRel").withRdfPredicate(URI.create("dependsOn")), + relationType("feedsA") + .withRdfPredicate(URI.create("https://example.org/f")), + relationType("feedsB") + .withRdfPredicate(URI.create("https://example.org/f")), + relationType("isA") + .withRdfPredicate( + URI.create("http://www.w3.org/2000/01/rdf-schema#subClassOf")), + relationType("oddFlags").withIsSymmetric(true).withIsAsymmetric(true), + relationType(DOTTED))), + "system"); + for (final RelationshipType type : types) { + // 2.1.0 stored the bare name as the FQN and hashed it whole. + type.setFullyQualifiedName(type.getName()); + handle + .createUpdate( + "INSERT INTO relationship_type_entity (fqnHash, json) VALUES (:fqnHash, " + + jsonValue() + + ")") + .bind("fqnHash", EntityUtil.hash(type.getName())) + .bind("json", JsonUtils.pojoToJson(type)) + .execute(); + } + } + + private static GlossaryTermRelationType relationType(final String name) { + return new GlossaryTermRelationType() + .withName(name) + .withDisplayName(name) + .withDescription(name) + .withCategory(RelationCategory.ASSOCIATIVE) + .withIsCrossGlossaryAllowed(true) + .withIsSystemDefined(false); + } + + private static void link( + final Handle handle, + final String from, + final String to, + final String entity, + final String relationType, + final String relationshipTypeId) { + handle + .createUpdate( + "INSERT INTO entity_relationship (fromId, toId, fromEntity, toEntity, relation," + + " relationType, json, relationshipId, relationshipTypeId) VALUES (:fromId, :toId," + + " :entity, :entity, :relation, :relationType, " + + jsonValue() + + ", :relationshipId, :relationshipTypeId)") + .bind("fromId", from) + .bind("toId", to) + .bind("entity", entity) + .bind("relation", RELATED_TO) + .bind("relationType", relationType) + .bind("json", JsonUtils.pojoToJson(Map.of("relationType", relationType))) + .bind("relationshipId", UUID.randomUUID().toString()) + .bind("relationshipTypeId", relationshipTypeId) + .execute(); + } + + private static boolean termLinksNameTheirType(final Handle handle) { + final Map idByName = + types(handle).stream() + .collect(Collectors.toMap(RelationshipType::getName, type -> type.getId().toString())); + return handle + .createQuery( + "SELECT relationType, relationshipTypeId, json FROM entity_relationship" + + " WHERE fromEntity = :entity") + .bind("entity", GLOSSARY_TERM) + .map( + (row, context) -> + idByName + .get(row.getString("relationType")) + .equals(row.getString("relationshipTypeId")) + && row.getString("relationType") + .equals( + JsonUtils.readTree(row.getString("json")) + .path("relationType") + .asText())) + .list() + .stream() + .allMatch(Boolean::booleanValue); + } + + private static List types(final Handle handle) { + return handle + .createQuery("SELECT json FROM relationship_type_entity") + .mapTo(String.class) + .map(json -> JsonUtils.readValue(json, RelationshipType.class)) + .list(); + } + + private static RelationshipType typeNamed(final Handle handle, final String name) { + return types(handle).stream() + .filter(type -> name.equals(type.getName())) + .findFirst() + .orElseThrow(); + } + + private static String typeId(final Handle handle, final String name) { + return typeNamed(handle, name).getId().toString(); + } + + private static String fqnHash(final Handle handle, final String name) { + return handle + .createQuery("SELECT fqnHash FROM relationship_type_entity WHERE name = :name") + .bind("name", name) + .mapTo(String.class) + .one(); + } + + private static Map typeJson(final Handle handle) { + final Map rows = new TreeMap<>(); + handle + .createQuery("SELECT name, fqnHash, json FROM relationship_type_entity") + .map( + (row, context) -> + Map.entry( + row.getString("name"), + row.getString("fqnHash") + JsonUtils.readTree(row.getString("json")))) + .forEach(row -> rows.put(row.getKey(), row.getValue())); + return rows; + } + + private static Map linkJson(final Handle handle) { + final Map rows = new TreeMap<>(); + handle + .createQuery( + "SELECT fromId, toId, relationType, relationshipTypeId, json FROM entity_relationship") + .map( + (row, context) -> + Map.entry( + row.getString("fromId") + ">" + row.getString("toId"), + row.getString("relationType") + + row.getString("relationshipTypeId") + + JsonUtils.readTree(row.getString("json")))) + .forEach(row -> rows.merge(row.getKey(), row.getValue(), (x, y) -> x + "," + y)); + return rows; + } + + private static Map links(final Handle handle) { + final Map links = new TreeMap<>(); + handle + .createQuery("SELECT fromId, toId, fromEntity, relationType FROM entity_relationship") + .map( + (row, context) -> + Map.entry( + row.getString("fromId") + + ">" + + row.getString("toId") + + ":" + + row.getString("fromEntity"), + row.getString("relationType"))) + .forEach(link -> links.merge(link.getKey(), link.getValue(), (x, y) -> x + "," + y)); + return links; + } + + private static String jsonValue() { + return ScratchDatabase.dialect() == ConnectionType.MYSQL ? ":json" : "CAST(:json AS jsonb)"; + } + + /** Column types as v001/v004, 1.13.0 (relationType + primary key) and 2.1.0 create them. */ + private static final List MYSQL_TABLES = + List.of( + """ + CREATE TABLE entity_relationship ( + fromId VARCHAR(36) NOT NULL, + toId VARCHAR(36) NOT NULL, + fromEntity VARCHAR(256) NOT NULL, + toEntity VARCHAR(256) NOT NULL, + relation TINYINT NOT NULL, + relationType VARCHAR(64) NOT NULL DEFAULT '', + json JSON, + deleted BOOLEAN NOT NULL DEFAULT FALSE, + relationshipId VARCHAR(36) DEFAULT NULL, + relationshipTypeId VARCHAR(36) DEFAULT NULL, + PRIMARY KEY (fromId, toId, relation, relationType), + UNIQUE KEY relationship_id_unique (relationshipId)) + """, + """ + CREATE TABLE relationship_type_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.id'))) STORED + NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.name'))) + STORED NOT NULL, + fqnHash VARCHAR(768) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + json JSON NOT NULL, + deleted TINYINT(1) GENERATED ALWAYS AS (json_extract(json, '$.deleted')) STORED, + PRIMARY KEY (id), + UNIQUE KEY relationship_type_fqn_hash_unique (fqnHash)) + DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci + """); + + private static final List POSTGRES_TABLES = + List.of( + """ + CREATE TABLE entity_relationship ( + fromId VARCHAR(36) NOT NULL, + toId VARCHAR(36) NOT NULL, + fromEntity VARCHAR(256) NOT NULL, + toEntity VARCHAR(256) NOT NULL, + relation SMALLINT NOT NULL, + relationType VARCHAR(64) NOT NULL DEFAULT '', + json JSONB, + deleted BOOLEAN NOT NULL DEFAULT FALSE, + relationshipId VARCHAR(36), + relationshipTypeId VARCHAR(36), + PRIMARY KEY (fromId, toId, relation, relationType), + UNIQUE (relationshipId)) + """, + """ + CREATE TABLE relationship_type_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json ->> 'name') STORED NOT NULL, + fqnHash VARCHAR(768) NOT NULL, + json JSONB NOT NULL, + deleted BOOLEAN GENERATED ALWAYS AS ((json ->> 'deleted')::boolean) STORED, + PRIMARY KEY (id), + CONSTRAINT relationship_type_fqn_hash_unique UNIQUE (fqnHash)) + """); +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ScratchDatabase.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ScratchDatabase.java new file mode 100644 index 000000000000..aa598681c817 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ScratchDatabase.java @@ -0,0 +1,68 @@ +package org.openmetadata.it.util; + +import java.util.UUID; +import java.util.function.Consumer; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.statement.SqlStatements; +import org.jdbi.v3.sqlobject.SqlObjectPlugin; +import org.jdbi.v3.sqlobject.SqlObjects; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.service.jdbi3.locator.ConnectionAwareAnnotationSqlLocator; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * An empty database on the suite's database server, for SQL and migration tests that need a schema + * they build themselves instead of the running server's. It uses the lane's dialect, so the MySQL + * and PostgreSQL lanes each cover theirs, and is dropped when the test body returns. + */ +public final class ScratchDatabase { + private ScratchDatabase() {} + + public static ConnectionType dialect() { + return TestSuiteBootstrap.getConnectionType(); + } + + public static void withDatabase(Consumer body) { + withJdbi(jdbi -> jdbi.useHandle(body::accept)); + } + + public static void withJdbi(Consumer body) { + JdbcDatabaseContainer server = TestSuiteBootstrap.getDatabaseContainer(); + ConnectionType dialect = dialect(); + String name = "scratch_" + UUID.randomUUID().toString().replace("-", ""); + Jdbi admin = connect(server, dialect, server.getDatabaseName()); + admin.useHandle(handle -> handle.execute("CREATE DATABASE " + name)); + try { + body.accept(connect(server, dialect, name)); + } finally { + admin.useHandle( + handle -> + handle.execute( + "DROP DATABASE " + + name + + (dialect == ConnectionType.POSTGRES ? " WITH (FORCE)" : ""))); + } + } + + private static Jdbi connect( + JdbcDatabaseContainer server, ConnectionType dialect, String database) { + boolean mysql = dialect == ConnectionType.MYSQL; + String url = + "jdbc:%s://%s:%d/%s%s" + .formatted( + mysql ? "mysql" : "postgresql", + server.getHost(), + server.getMappedPort(mysql ? 3306 : 5432), + database, + mysql ? "?allowPublicKeyRetrieval=true&useSSL=false" : ""); + // MySQLContainer gives root the same password as its user; only root may create databases. + Jdbi jdbi = Jdbi.create(url, mysql ? "root" : server.getUsername(), server.getPassword()); + jdbi.installPlugin(new SqlObjectPlugin()); + jdbi.getConfig(SqlStatements.class).setUnusedBindingAllowed(true); + jdbi.getConfig(SqlObjects.class) + .setSqlLocator(new ConnectionAwareAnnotationSqlLocator(dialect.label)); + return jdbi; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v212/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v212/Migration.java index 3df736ed0f3b..eaa5c7538811 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v212/Migration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v212/Migration.java @@ -21,6 +21,7 @@ import org.openmetadata.service.migration.utils.v212.DataProductLineageRebuild; import org.openmetadata.service.migration.utils.v212.DataProductLineageSelfLoopRepair; import org.openmetadata.service.migration.utils.v212.LogicalTestSuitePipelineMigration; +import org.openmetadata.service.migration.utils.v212.RelationshipTypeRepair; public class Migration extends MigrationProcessImpl { @@ -30,6 +31,13 @@ public Migration(final MigrationFile migrationFile) { @Override public void runDataMigration() { + // 2.1.0 stored relationship types without the checks a 2.1 write runs, so some could not be + // saved, blocked a seed type, or were named by term links with no type behind them. + runOnce( + migrationDAO, + getVersion(), + RelationshipTypeRepair.STEP_NAME, + () -> RelationshipTypeRepair.repair(handle, MYSQL)); runOnce( migrationDAO, getVersion(), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v212/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v212/Migration.java index b273f6e2c9fb..f5f0ababfb00 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v212/Migration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v212/Migration.java @@ -21,6 +21,7 @@ import org.openmetadata.service.migration.utils.v212.DataProductLineageRebuild; import org.openmetadata.service.migration.utils.v212.DataProductLineageSelfLoopRepair; import org.openmetadata.service.migration.utils.v212.LogicalTestSuitePipelineMigration; +import org.openmetadata.service.migration.utils.v212.RelationshipTypeRepair; public class Migration extends MigrationProcessImpl { @@ -30,6 +31,13 @@ public Migration(final MigrationFile migrationFile) { @Override public void runDataMigration() { + // 2.1.0 stored relationship types without the checks a 2.1 write runs, so some could not be + // saved, blocked a seed type, or were named by term links with no type behind them. + runOnce( + migrationDAO, + getVersion(), + RelationshipTypeRepair.STEP_NAME, + () -> RelationshipTypeRepair.repair(handle, POSTGRES)); runOnce( migrationDAO, getVersion(), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/OntologyMigration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/OntologyMigration.java index 271f555618c4..506b7c5488bb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/OntologyMigration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/OntologyMigration.java @@ -13,38 +13,403 @@ package org.openmetadata.service.migration.utils.v210; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.time.Clock; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import java.util.stream.StreamSupport; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Handle; import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; import org.openmetadata.schema.entity.data.RelationshipType; +import org.openmetadata.schema.type.Relationship; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.jdbi3.locator.ConnectionType; import org.openmetadata.service.ontology.LegacyRelationshipTypeMapper; -import org.openmetadata.service.util.EntityUtil; +import org.openmetadata.service.util.FullyQualifiedName; @Slf4j public final class OntologyMigration { static final String SETTING_NAME = "glossaryTermRelationSettings"; private static final String SYSTEM_USER = "system"; + private static final String RELATION_TYPES = "relationTypes"; + private static final String NAME = "name"; + private static final String DISPLAY_NAME = "displayName"; + private static final String DESCRIPTION = "description"; + private static final String INVERSE_RELATION = "inverseRelation"; + private static final String IS_SYSTEM_DEFINED = "isSystemDefined"; + private static final String IS_SYMMETRIC = "isSymmetric"; + private static final String CARDINALITY = "cardinality"; + private static final List SHARED_FIELDS = + List.of( + "category", + "isCrossGlossaryAllowed", + "isTransitive", + "isReflexive", + "isIrreflexive", + "isAsymmetric"); + private static final List> MIRRORED_FIELDS = + List.of( + List.of("sourceMax", "targetMax"), + List.of("isFunctional", "isInverseFunctional"), + List.of("domain", "range")); + private static final Map MIRRORED_CARDINALITY = + Map.of("ONE_TO_MANY", "MANY_TO_ONE", "MANY_TO_ONE", "ONE_TO_MANY"); + private static final Pattern VALID_NAME = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$"); + private static final Pattern WORD_SEPARATOR = Pattern.compile("[^A-Za-z0-9]+"); + // entity_relationship.relationType is VARCHAR(64); this leaves room for a uniqueness suffix. + private static final int MAX_GENERATED_NAME_LENGTH = 60; + private static final String GENERATED_NAME_PREFIX = "inverseOf"; + private static final String GENERATED_DESCRIPTION_PREFIX = "Inverse of "; + private static final String GLOSSARY_TERM = "glossaryTerm"; + private static final String TERM_LINKS = + " stale.fromEntity = :entity AND stale.toEntity = :entity AND stale.relation = :relation" + + " AND %s = :stored"; + // The inequality stops a case-insensitive collation from matching a stale row against itself. + private static final String SAME_LINK_UNDER_RESOLVED_TYPE = + " kept.fromId = stale.fromId AND kept.toId = stale.toId AND kept.relation = stale.relation" + + " AND %s = :resolved AND kept.relationType <> stale.relationType"; + // MySQL compares byte for byte, so one stored name never matches another in a different case. + private static final String MYSQL_EXACT = + "CONVERT(%s.relationType USING utf8mb4) COLLATE utf8mb4_bin"; + private static final String POSTGRES_EXACT = "%s.relationType"; + + /** A stored term-link relation type renamed to the type its inverse now resolves to. */ + record InverseRename(String storedName, String resolvedName) {} private OntologyMigration() {} + /** + * Converts the 2.0 settings once. Any change to this version's code re-runs it on a cluster + * already at 2.1.0, where the settings are stale: types stored by then are kept as 2.1 left + * them (ADR:2026-12-04-upgrade-turns-free-text-relation-inverses-into-relationship-types). + */ public static void migrateRelationshipTypes( final Handle handle, final ConnectionType connectionType) { + handle.useTransaction(transaction -> convertOnce(transaction, connectionType)); + } + + private static void convertOnce(final Handle handle, final ConnectionType connectionType) { + if (hasRelationshipTypes(handle)) { + LOG.info("Relationship types are already stored; the 2.0 settings are not converted again"); + } else { + convert(handle, connectionType); + } + } + + private static void convert(final Handle handle, final ConnectionType connectionType) { + repairUnresolvedInverses(handle, connectionType); final GlossaryTermRelationSettings settings = loadSettings(handle); final LegacyRelationshipTypeMapper mapper = new LegacyRelationshipTypeMapper(Clock.systemUTC()); final List relationshipTypes = mapper.map(settings, SYSTEM_USER); - relationshipTypes.forEach(type -> upsert(handle, connectionType, type)); + relationshipTypes.forEach(type -> insertRelationshipType(handle, connectionType, type)); LOG.info("Migrated {} governed ontology relationship types", relationshipTypes.size()); } + private static boolean hasRelationshipTypes(final Handle handle) { + return handle + .createQuery("SELECT COUNT(*) FROM relationship_type_entity") + .mapTo(Long.class) + .one() + > 0; + } + static GlossaryTermRelationSettings loadSettings(final Handle handle) { final String json = readSettingsJson(handle); return JsonUtils.readValue(json, GlossaryTermRelationSettings.class); } + /** + * Points each free-text 2.0 inverse at a real type and renames the links stored under its text; + * links go first so an interrupted run repeats the repair + * (ADR:2026-12-04-upgrade-turns-free-text-relation-inverses-into-relationship-types). + */ + private static void repairUnresolvedInverses( + final Handle handle, final ConnectionType connectionType) { + final ObjectNode settings = (ObjectNode) JsonUtils.readTree(readSettingsJson(handle)); + final String stored = settings.toString(); + final List duplicates = dropDuplicateNames(settings); + if (!duplicates.isEmpty()) { + LOG.warn("Glossary term relation types defined more than once keep one each: {}", duplicates); + } + final List renames = resolveUnresolvedInverses(settings); + renames.forEach(rename -> renameStoredRelationType(handle, connectionType, rename)); + if (!stored.equals(settings.toString())) { + writeSettings(handle, connectionType, settings); + LOG.warn("Resolved glossary term relation inverses that named no type: {}", renames); + } + } + + /** + * Keeps one definition per name, as each name becomes one stored type: the system-defined one, + * else the first. Returns the names that had more than one. + */ + static List dropDuplicateNames(final ObjectNode settings) { + final List duplicates = new ArrayList<>(); + if (settings.path(RELATION_TYPES) instanceof ArrayNode types) { + final Map kept = new LinkedHashMap<>(); + for (final ObjectNode type : objectsOf(types)) { + final String name = type.path(NAME).asText(); + final ObjectNode first = kept.putIfAbsent(name, type); + if (first != null) { + duplicates.add(name); + kept.put(name, !isSystemDefined(first) && isSystemDefined(type) ? type : first); + } + } + types.removeAll(); + kept.values().forEach(types::add); + } + return List.copyOf(duplicates); + } + + private static boolean isSystemDefined(final ObjectNode type) { + return type.path(IS_SYSTEM_DEFINED).asBoolean(false); + } + + static List resolveUnresolvedInverses(final ObjectNode settings) { + final Map renames = new LinkedHashMap<>(); + final Map createdByText = new HashMap<>(); + if (settings.path(RELATION_TYPES) instanceof ArrayNode types) { + for (final ObjectNode type : objectsOf(types)) { + resolveInverse(types, type, renames, createdByText); + } + } + return List.copyOf(renames.values()); + } + + private static void resolveInverse( + final ArrayNode types, + final ObjectNode type, + final Map renames, + final Map createdByText) { + final String inverse = type.path(INVERSE_RELATION).asText(null); + final boolean blank = inverse != null && inverse.isBlank(); + final boolean unresolved = inverse != null && !blank && findByName(types, inverse).isEmpty(); + if (blank) { + type.remove(INVERSE_RELATION); + } + if (unresolved) { + pointAtResolvedType(types, type, inverse, renames, createdByText); + } + } + + private static void pointAtResolvedType( + final ArrayNode types, + final ObjectNode type, + final String inverse, + final Map renames, + final Map createdByText) { + final String text = inverse.strip(); + // A symmetric relation is its own inverse, so links stored under the text belong to it. + // Otherwise match by name only, as 2.0 did (a display name is a label, not a key); types + // naming the same text share the one type created for it. + final ObjectNode target = + type.path(IS_SYMMETRIC).asBoolean(false) + ? type + : findByNameIgnoringCase(types, text) + .orElseGet( + () -> + createdByText.computeIfAbsent( + text.toLowerCase(Locale.ROOT), key -> addInverse(types, type, text))); + final String resolvedName = target.path(NAME).asText(); + type.put(INVERSE_RELATION, resolvedName); + renames.putIfAbsent(inverse, new InverseRename(inverse, resolvedName)); + } + + private static ObjectNode addInverse( + final ArrayNode types, final ObjectNode base, final String inverseText) { + final String name = uniqueName(types, inverseText, base.path(NAME).asText()); + final ObjectNode inverse = types.addObject(); + inverse.put(NAME, name); + inverse.put(DISPLAY_NAME, inverseText); + inverse.put(DESCRIPTION, GENERATED_DESCRIPTION_PREFIX + base.path(DISPLAY_NAME).asText("")); + inverse.put(INVERSE_RELATION, base.path(NAME).asText()); + inverse.put(IS_SYSTEM_DEFINED, false); + copyDirectionalConstraints(base, inverse); + return inverse; + } + + private static void copyDirectionalConstraints(final ObjectNode base, final ObjectNode inverse) { + SHARED_FIELDS.forEach(field -> copyField(base, field, inverse, field)); + MIRRORED_FIELDS.forEach( + pair -> { + copyField(base, pair.get(0), inverse, pair.get(1)); + copyField(base, pair.get(1), inverse, pair.get(0)); + }); + final String cardinality = base.path(CARDINALITY).asText(null); + if (cardinality != null) { + inverse.put(CARDINALITY, MIRRORED_CARDINALITY.getOrDefault(cardinality, cardinality)); + } + } + + private static void copyField( + final ObjectNode from, final String fromField, final ObjectNode to, final String toField) { + final JsonNode value = from.get(fromField); + if (value != null && !value.isNull()) { + to.set(toField, value.deepCopy()); + } + } + + private static String uniqueName( + final ArrayNode types, final String inverseText, final String baseName) { + return uniqueName( + inverseText, + GENERATED_NAME_PREFIX + capitalize(baseName), + name -> findByNameIgnoringCase(types, name).isPresent()); + } + + /** + * A relation type name made from {@code text}, else {@code fallback}, suffixed until {@code + * taken} accepts it. + */ + private static String uniqueName( + final String text, final String fallback, final Predicate taken) { + final String camelCase = camelCase(text); + final String candidate = VALID_NAME.matcher(camelCase).matches() ? camelCase : fallback; + final String stem = + candidate.substring(0, Math.min(candidate.length(), MAX_GENERATED_NAME_LENGTH)); + String name = stem; + for (int suffix = 2; taken.test(name); suffix++) { + name = stem + suffix; + } + return name; + } + + private static String camelCase(final String text) { + final StringBuilder name = new StringBuilder(); + for (final String word : WORD_SEPARATOR.split(text.strip())) { + name.append(name.isEmpty() ? uncapitalize(word) : capitalize(word)); + } + return name.toString(); + } + + private static String capitalize(final String word) { + return word.isEmpty() + ? word + : word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1); + } + + private static String uncapitalize(final String word) { + return word.isEmpty() + ? word + : word.substring(0, 1).toLowerCase(Locale.ROOT) + word.substring(1); + } + + private static Optional findByName(final ArrayNode types, final String name) { + return objectsOf(types).stream() + .filter(type -> name.equals(type.path(NAME).asText(null))) + .findFirst(); + } + + private static Optional findByNameIgnoringCase( + final ArrayNode types, final String name) { + return objectsOf(types).stream() + .filter(type -> name.equalsIgnoreCase(type.path(NAME).asText(null))) + .findFirst(); + } + + private static List objectsOf(final ArrayNode types) { + return StreamSupport.stream(types.spliterator(), false) + .filter(ObjectNode.class::isInstance) + .map(ObjectNode.class::cast) + .toList(); + } + + private static void renameStoredRelationType( + final Handle handle, final ConnectionType connectionType, final InverseRename rename) { + renameTermLinks(handle, connectionType, rename.storedName(), rename.resolvedName()); + } + + /** Moves the term links stored under {@code storedName} onto {@code resolvedName}. */ + private static void renameTermLinks( + final Handle handle, + final ConnectionType connectionType, + final String storedName, + final String resolvedName) { + final InverseRename rename = new InverseRename(storedName, resolvedName); + executeOnTermLinks(handle, deleteDuplicateLinksSql(connectionType), rename); + executeOnTermLinks(handle, renameLinksSql(connectionType), rename); + } + + private static String deleteDuplicateLinksSql(final ConnectionType connectionType) { + return switch (connectionType) { + case MYSQL -> "DELETE stale FROM entity_relationship stale JOIN entity_relationship kept" + + " ON" + + sameLinkUnderResolvedType(connectionType) + + " WHERE" + + termLinks(connectionType); + case POSTGRES -> "DELETE FROM entity_relationship stale USING entity_relationship kept" + + " WHERE" + + sameLinkUnderResolvedType(connectionType) + + " AND" + + termLinks(connectionType); + }; + } + + private static String renameLinksSql(final ConnectionType connectionType) { + return switch (connectionType) { + case MYSQL -> "UPDATE entity_relationship stale SET stale.relationType = :resolved," + + " stale.json = JSON_SET(COALESCE(stale.json, JSON_OBJECT()), '$.relationType'," + + " :resolved) WHERE" + + termLinks(connectionType); + case POSTGRES -> "UPDATE entity_relationship stale SET relationType = :resolved," + + " json = jsonb_set(COALESCE(stale.json, '{}'::jsonb), '{relationType}'," + + " to_jsonb(CAST(:resolved AS text))) WHERE" + + termLinks(connectionType); + }; + } + + private static String termLinks(final ConnectionType connectionType) { + return TERM_LINKS.formatted(exactRelationType(connectionType, "stale")); + } + + private static String sameLinkUnderResolvedType(final ConnectionType connectionType) { + return SAME_LINK_UNDER_RESOLVED_TYPE.formatted(exactRelationType(connectionType, "kept")); + } + + private static String exactRelationType(final ConnectionType connectionType, final String alias) { + return switch (connectionType) { + case MYSQL -> MYSQL_EXACT.formatted(alias); + case POSTGRES -> POSTGRES_EXACT.formatted(alias); + }; + } + + private static void executeOnTermLinks( + final Handle handle, final String sql, final InverseRename rename) { + handle + .createUpdate(sql) + .bind("entity", GLOSSARY_TERM) + .bind("relation", Relationship.RELATED_TO.ordinal()) + .bind("stored", rename.storedName()) + .bind("resolved", rename.resolvedName()) + .execute(); + } + + private static void writeSettings( + final Handle handle, final ConnectionType connectionType, final ObjectNode settings) { + final String sql = + switch (connectionType) { + case MYSQL -> "UPDATE openmetadata_settings SET json = :json" + + " WHERE configType = :configType"; + case POSTGRES -> "UPDATE openmetadata_settings SET json = CAST(:json AS jsonb)" + + " WHERE configType = :configType"; + }; + handle + .createUpdate(sql) + .bind("json", settings.toString()) + .bind("configType", SETTING_NAME) + .execute(); + } + private static String readSettingsJson(final Handle handle) { return handle .createQuery("SELECT json FROM openmetadata_settings WHERE configType = :configType") @@ -54,25 +419,22 @@ private static String readSettingsJson(final Handle handle) { .orElse("{}"); } - private static void upsert( + /** Stores a type under the FQN hash the repository looks it up by. */ + private static void insertRelationshipType( final Handle handle, final ConnectionType connectionType, final RelationshipType relationshipType) { - final String sql = upsertSql(connectionType); + final String sql = + switch (connectionType) { + case MYSQL -> "INSERT INTO relationship_type_entity (fqnHash, json)" + + " VALUES (:fqnHash, :json)"; + case POSTGRES -> "INSERT INTO relationship_type_entity (fqnHash, json)" + + " VALUES (:fqnHash, CAST(:json AS jsonb))"; + }; handle .createUpdate(sql) - .bind("fqnHash", EntityUtil.hash(relationshipType.getFullyQualifiedName())) + .bind("fqnHash", FullyQualifiedName.buildHash(relationshipType.getFullyQualifiedName())) .bind("json", JsonUtils.pojoToJson(relationshipType)) .execute(); } - - private static String upsertSql(final ConnectionType connectionType) { - return switch (connectionType) { - case MYSQL -> "INSERT INTO relationship_type_entity (fqnHash, json) VALUES (:fqnHash, :json) " - + "ON DUPLICATE KEY UPDATE json = VALUES(json)"; - case POSTGRES -> "INSERT INTO relationship_type_entity (fqnHash, json) " - + "VALUES (:fqnHash, CAST(:json AS jsonb)) " - + "ON CONFLICT (fqnHash) DO UPDATE SET json = EXCLUDED.json"; - }; - } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepair.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepair.java new file mode 100644 index 000000000000..90bca68fdbbd --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepair.java @@ -0,0 +1,657 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.migration.utils.v212; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.jdbi.v3.core.Handle; +import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * Repairs the relationship types 2.1.0 converted without the validation every 2.1 write runs, so + * each can be saved again, the seed types can be created, and every glossary term link names a + * stored type (ADR:2026-12-04-upgrade-repairs-relationship-types-2-1-rejects). + */ +@Slf4j +public final class RelationshipTypeRepair { + public static final String STEP_NAME = "relationshipTypeRepair"; + private static final String GLOSSARY_TERM = "glossaryTerm"; + private static final String RELATIONSHIP_TYPE = "relationshipType"; + // The type a glossary term link reads as when it stores none. + private static final String DEFAULT_RELATION_TYPE = "relatedTo"; + private static final String CREATED_NAME_FALLBACK = "relation"; + private static final String DEFAULT_PREDICATE_BASE = "https://open-metadata.org/ontology/"; + private static final String SYSTEM_USER = "system"; + private static final String ID = "id"; + private static final String TYPE = "type"; + private static final String NAME = "name"; + private static final String FQN = "fullyQualifiedName"; + private static final String DISPLAY_NAME = "displayName"; + private static final String DELETED = "deleted"; + private static final String SYSTEM_DEFINED = "systemDefined"; + private static final String CHARACTERISTICS = "characteristics"; + private static final String CARDINALITY = "cardinality"; + private static final String SOURCE_MAX = "sourceMax"; + private static final String TARGET_MAX = "targetMax"; + private static final String INVERSE = "inverse"; + private static final String RDF_PREDICATE = "rdfPredicate"; + private static final String IRI = "iri"; + private static final String SYMMETRIC = "SYMMETRIC"; + private static final String ASYMMETRIC = "ASYMMETRIC"; + private static final String REFLEXIVE = "REFLEXIVE"; + private static final String IRREFLEXIVE = "IRREFLEXIVE"; + private static final String FUNCTIONAL = "FUNCTIONAL"; + private static final String INVERSE_FUNCTIONAL = "INVERSE_FUNCTIONAL"; + private static final List> INCOMPATIBLE = + List.of( + List.of(SYMMETRIC, ASYMMETRIC), + List.of(REFLEXIVE, IRREFLEXIVE), + List.of(ASYMMETRIC, REFLEXIVE)); + private static final Pattern VALID_NAME = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$"); + private static final Pattern WORD_SEPARATOR = Pattern.compile("[^A-Za-z0-9]+"); + // entity_relationship.relationType is VARCHAR(64); this leaves room for a uniqueness suffix. + private static final int MAX_CREATED_NAME_LENGTH = 60; + + /** The 2.1.2 seed types by predicate: each predicate stays free for its seed to be created. */ + static final Map SEED_PREDICATES = + Map.ofEntries( + Map.entry("https://open-metadata.org/ontology/relatedTo", "relatedTo"), + Map.entry("http://www.w3.org/2004/02/skos/core#exactMatch", "synonym"), + Map.entry("https://open-metadata.org/ontology/antonym", "antonym"), + Map.entry("http://www.w3.org/2004/02/skos/core#broader", "broader"), + Map.entry("http://www.w3.org/2004/02/skos/core#narrower", "narrower"), + Map.entry("https://open-metadata.org/ontology/partOf", "partOf"), + Map.entry("https://open-metadata.org/ontology/hasPart", "hasPart"), + Map.entry("https://open-metadata.org/ontology/calculatedFrom", "calculatedFrom"), + Map.entry("https://open-metadata.org/ontology/usedToCalculate", "usedToCalculate"), + Map.entry("http://www.w3.org/2000/01/rdf-schema#seeAlso", "seeAlso"), + Map.entry("http://www.w3.org/2000/01/rdf-schema#subClassOf", "subClassOf"), + Map.entry("https://open-metadata.org/ontology/superClassOf", "superClassOf")); + + // Who keeps a predicate several types hold: live before deleted, system before custom, the + // type whose own default it is, then by name. + private static final Comparator KEEPS_PREDICATE_FIRST = + Comparator.comparing((ObjectNode type) -> type.path(DELETED).asBoolean(false)) + .thenComparing(type -> !type.path(SYSTEM_DEFINED).asBoolean(false)) + .thenComparing(type -> !isOwnDefaultPredicate(type)) + .thenComparing(RelationshipTypeRepair::name); + + /** Term links stored under {@code storedName} move onto the type named {@code resolvedName}. */ + record LinkRename(String storedName, String resolvedName) {} + + record Plan(List changed, List created, List renames) {} + + private RelationshipTypeRepair() {} + + public static void repair(final Handle handle, final ConnectionType connectionType) { + handle.useTransaction(transaction -> repairWithin(transaction, connectionType)); + } + + private static void repairWithin(final Handle handle, final ConnectionType connectionType) { + final Plan plan = plan(loadTypes(handle), storedLinkTypes(handle, connectionType)); + plan.changed().forEach(type -> update(handle, connectionType, type)); + plan.created().forEach(type -> insert(handle, connectionType, type)); + plan.renames().forEach(rename -> renameTermLinks(handle, connectionType, rename)); + relinkTermLinks(handle, connectionType); + LOG.info( + "Repaired {} relationship types, created {}, moved term links stored under {}", + plan.changed().size(), + plan.created().size(), + plan.renames()); + } + + /** Repairs {@code types} in place and returns what to write. */ + static Plan plan(final List types, final Set storedLinkTypes) { + final Map before = new HashMap<>(); + types.forEach(type -> before.put(id(type), type.deepCopy())); + types.forEach(RelationshipTypeRepair::repairDefinition); + refreshInverseReferences(types); + final Set taken = assignPredicates(types); + final List created = new ArrayList<>(); + final List renames = resolveStoredLinkTypes(types, storedLinkTypes, taken, created); + final List changed = + types.stream().filter(type -> !before.get(id(type)).equals(type)).toList(); + return new Plan(changed, List.copyOf(created), renames); + } + + private static void repairDefinition(final ObjectNode type) { + type.put(FQN, FullyQualifiedName.quoteName(name(type))); + dropIncompatibleCharacteristics(type); + limitFunctionalCardinality(type); + repairSelfInverse(type); + } + + private static void dropIncompatibleCharacteristics(final ObjectNode type) { + for (final List pair : INCOMPATIBLE) { + if (has(type, pair.get(0)) && has(type, pair.get(1))) { + removeCharacteristics(type, pair); + LOG.warn("Relationship type '{}' declared {} together; both are cleared", name(type), pair); + } + } + } + + private static void limitFunctionalCardinality(final ObjectNode type) { + limitToOne(type, FUNCTIONAL, SOURCE_MAX); + limitToOne(type, INVERSE_FUNCTIONAL, TARGET_MAX); + } + + private static void limitToOne( + final ObjectNode type, final String characteristic, final String field) { + final JsonNode limit = type.path(CARDINALITY).path(field); + if (has(type, characteristic) && !(limit.isInt() && limit.asInt() == 1)) { + cardinalityOf(type).put(field, 1); + LOG.warn("{} relationship type '{}' now sets {} to 1", characteristic, name(type), field); + } + } + + private static ObjectNode cardinalityOf(final ObjectNode type) { + return type.get(CARDINALITY) instanceof ObjectNode cardinality + ? cardinality + : type.putObject(CARDINALITY); + } + + private static void repairSelfInverse(final ObjectNode type) { + final boolean selfInverse = isSelf(type, type.path(INVERSE)); + if (has(type, SYMMETRIC) && !selfInverse) { + LOG.warn( + "Symmetric relationship type '{}' named '{}' as its inverse; it is now its own inverse", + name(type), + type.path(INVERSE).path(NAME).asText(null)); + type.set(INVERSE, referenceTo(type)); + } + if (has(type, ASYMMETRIC) && selfInverse) { + removeCharacteristics(type, List.of(ASYMMETRIC)); + LOG.warn("Relationship type '{}' is its own inverse; asymmetric is cleared", name(type)); + } + } + + /** An inverse reference keeps the name and FQN of the type it points at. */ + private static void refreshInverseReferences(final List types) { + final Map byId = + types.stream().collect(Collectors.toMap(RelationshipTypeRepair::id, Function.identity())); + for (final ObjectNode type : types) { + final ObjectNode target = + type.get(INVERSE) instanceof ObjectNode inverse + ? byId.get(inverse.path(ID).asText()) + : null; + if (target != null) { + ((ObjectNode) type.get(INVERSE)).put(NAME, name(target)).put(FQN, fqn(target)); + } + } + } + + /** + * Leaves every type with an absolute predicate of its own: a seed type's predicate goes to that + * seed, so its seed can be created, and any other predicate to one holder. Returns the + * predicates now held. + */ + private static Set assignPredicates(final List types) { + final Set taken = new HashSet<>(SEED_PREDICATES.keySet()); + types.stream().sorted(KEEPS_PREDICATE_FIRST).forEach(type -> keepOrMovePredicate(type, taken)); + return taken; + } + + private static void keepOrMovePredicate(final ObjectNode type, final Set taken) { + final String predicate = type.path(RDF_PREDICATE).asText(null); + final boolean absolute = isAbsolute(predicate); + final boolean seedHolder = absolute && name(type).equals(SEED_PREDICATES.get(predicate)); + if (absolute && (seedHolder || !taken.contains(predicate))) { + taken.add(predicate); + } else { + final String assigned = assignDefaultPredicate(type, taken); + LOG.warn( + "Relationship type '{}' moved from RDF predicate '{}' to '{}': it was not absolute or" + + " another type governs it", + name(type), + predicate, + assigned); + } + } + + private static String assignDefaultPredicate(final ObjectNode type, final Set taken) { + final String previous = type.path(RDF_PREDICATE).asText(null); + String predicate = defaultPredicate(name(type)); + for (int suffix = 2; taken.contains(predicate); suffix++) { + predicate = defaultPredicate(name(type) + suffix); + } + type.put(RDF_PREDICATE, predicate); + if (!type.hasNonNull(IRI) || type.path(IRI).asText().equals(previous)) { + type.put(IRI, predicate); + } + taken.add(predicate); + return predicate; + } + + /** The predicate 2.1 gives a type that declares none; the name may hold a space. */ + private static String defaultPredicate(final String name) { + return DEFAULT_PREDICATE_BASE + URLEncoder.encode(name, UTF_8).replace("+", "%20"); + } + + private static boolean isOwnDefaultPredicate(final ObjectNode type) { + return defaultPredicate(name(type)).equals(type.path(RDF_PREDICATE).asText(null)); + } + + private static boolean isAbsolute(final String predicate) { + boolean absolute = false; + if (predicate != null) { + try { + absolute = new URI(predicate).isAbsolute(); + } catch (URISyntaxException invalid) { + absolute = false; + } + } + return absolute; + } + + /** + * Points each stored link type that names no stored type at one: a live type it names in another + * case, else a type created for it. A blank one reads as relatedTo. + */ + private static List resolveStoredLinkTypes( + final List types, + final Set storedLinkTypes, + final Set taken, + final List created) { + final List known = new ArrayList<>(types); + final Set names = + types.stream().map(RelationshipTypeRepair::name).collect(Collectors.toSet()); + return storedLinkTypes.stream() + .filter(stored -> !names.contains(stored)) + .sorted() + .map(stored -> resolveStoredLinkType(known, stored, taken, created)) + .toList(); + } + + private static LinkRename resolveStoredLinkType( + final List known, + final String stored, + final Set taken, + final List created) { + final String text = stored.isBlank() ? DEFAULT_RELATION_TYPE : stored.strip(); + final ObjectNode target = + findLive(known, text) + .or(() -> createdFor(created, text)) + .orElseGet(() -> createFor(known, text, taken, created)); + return new LinkRename(stored, name(target)); + } + + // Match by name only, as 2.0 resolved link types: a display name is a label, not a type's key. + private static Optional findLive(final List known, final String text) { + return known.stream() + .filter(type -> !type.path(DELETED).asBoolean(false)) + .filter(type -> name(type).equalsIgnoreCase(text)) + .findFirst(); + } + + // Texts differing only in case share the type this run created for the first of them. + private static Optional createdFor( + final List created, final String text) { + return created.stream() + .filter(type -> text.equalsIgnoreCase(type.path(DISPLAY_NAME).asText(null))) + .findFirst(); + } + + private static ObjectNode createFor( + final List known, + final String text, + final Set taken, + final List created) { + final String name = + uniqueName( + text, + candidate -> known.stream().anyMatch(type -> name(type).equalsIgnoreCase(candidate))); + final ObjectNode type = newAssociativeType(name, text); + assignDefaultPredicate(type, taken); + known.add(type); + created.add(type); + LOG.warn( + "Created relationship type '{}' for glossary term links stored as '{}', which named no type", + name, + text); + return type; + } + + /** A custom associative type, stored as 2.1.0 stored one converted from 2.0. */ + private static ObjectNode newAssociativeType(final String name, final String text) { + final ObjectNode type = JsonNodeFactory.instance.objectNode(); + type.put(ID, stableId(name).toString()); + type.put(NAME, name); + type.put(FQN, FullyQualifiedName.quoteName(name)); + type.put(DISPLAY_NAME, text); + type.put( + "description", + "Created on upgrade for glossary term relations stored as '" + + text + + "', which named no relation type"); + type.put("category", "CUSTOM"); + type.putArray("domain"); + type.putArray("range"); + type.putArray(CHARACTERISTICS); + type.put("crossGlossaryAllowed", true); + type.put("paletteKey", "BLUE"); + type.put(SYSTEM_DEFINED, false); + type.put("entityStatus", "Approved"); + type.put("version", 0.1); + type.put("updatedAt", System.currentTimeMillis()); + type.put("updatedBy", SYSTEM_USER); + type.put(DELETED, false); + type.put("provider", "user"); + return type; + } + + // The id 2.1 derives from a type's name, so a lookup that falls back to it finds this row. + private static UUID stableId(final String name) { + return UUID.nameUUIDFromBytes((RELATIONSHIP_TYPE + ':' + name).getBytes(UTF_8)); + } + + /** A type name made from {@code text}, else {@code relation}, suffixed until it is free. */ + private static String uniqueName(final String text, final Predicate taken) { + final String camelCase = camelCase(text); + final String candidate = + VALID_NAME.matcher(camelCase).matches() ? camelCase : CREATED_NAME_FALLBACK; + final String stem = + candidate.substring(0, Math.min(candidate.length(), MAX_CREATED_NAME_LENGTH)); + String name = stem; + for (int suffix = 2; taken.test(name); suffix++) { + name = stem + suffix; + } + return name; + } + + private static String camelCase(final String text) { + final StringBuilder name = new StringBuilder(); + for (final String word : WORD_SEPARATOR.split(text.strip())) { + if (!word.isEmpty()) { + final String first = word.substring(0, 1); + name.append( + name.isEmpty() ? first.toLowerCase(Locale.ROOT) : first.toUpperCase(Locale.ROOT)) + .append(word.substring(1)); + } + } + return name.toString(); + } + + private static ObjectNode referenceTo(final ObjectNode type) { + final ObjectNode reference = JsonNodeFactory.instance.objectNode(); + reference.put(ID, id(type)); + reference.put(TYPE, RELATIONSHIP_TYPE); + reference.put(NAME, name(type)); + reference.put(FQN, fqn(type)); + return reference; + } + + private static boolean isSelf(final ObjectNode type, final JsonNode reference) { + return reference.isObject() + && (id(type).equals(reference.path(ID).asText()) + || name(type).equals(reference.path(NAME).asText())); + } + + private static boolean has(final ObjectNode type, final String characteristic) { + boolean has = false; + for (final JsonNode value : type.path(CHARACTERISTICS)) { + has |= characteristic.equals(value.asText()); + } + return has; + } + + private static void removeCharacteristics( + final ObjectNode type, final Collection removed) { + final ArrayNode kept = JsonNodeFactory.instance.arrayNode(); + type.path(CHARACTERISTICS) + .forEach( + value -> { + if (!removed.contains(value.asText())) { + kept.add(value); + } + }); + type.set(CHARACTERISTICS, kept); + } + + private static String id(final ObjectNode type) { + return type.path(ID).asText(); + } + + private static String name(final ObjectNode type) { + return type.path(NAME).asText(); + } + + private static String fqn(final ObjectNode type) { + return type.path(FQN).asText(); + } + + private static List loadTypes(final Handle handle) { + return handle + .createQuery("SELECT json FROM relationship_type_entity") + .mapTo(String.class) + .map(json -> (ObjectNode) JsonUtils.readTree(json)) + .list(); + } + + /** Read byte for byte, so a case-insensitive collation cannot fold two stored names into one. */ + private static Set storedLinkTypes( + final Handle handle, final ConnectionType connectionType) { + return handle + .createQuery( + "SELECT DISTINCT " + + exactRelationType(connectionType, "link") + + " AS relationType FROM entity_relationship link WHERE link.fromEntity = :entity" + + " AND link.toEntity = :entity AND link.relation = :relation") + .bind("entity", GLOSSARY_TERM) + .bind("relation", Relationship.RELATED_TO.ordinal()) + .mapTo(String.class) + .collect(Collectors.toSet()); + } + + private static void update( + final Handle handle, final ConnectionType connectionType, final ObjectNode type) { + handle + .createUpdate( + "UPDATE relationship_type_entity SET json = " + + jsonValue(connectionType) + + ", fqnHash = :fqnHash WHERE id = :id") + .bind("json", type.toString()) + .bind("fqnHash", FullyQualifiedName.buildHash(fqn(type))) + .bind("id", id(type)) + .execute(); + } + + private static void insert( + final Handle handle, final ConnectionType connectionType, final ObjectNode type) { + handle + .createUpdate( + "INSERT INTO relationship_type_entity (fqnHash, json) VALUES (:fqnHash, " + + jsonValue(connectionType) + + ")") + .bind("fqnHash", FullyQualifiedName.buildHash(fqn(type))) + .bind("json", type.toString()) + .execute(); + } + + private static String jsonValue(final ConnectionType connectionType) { + return switch (connectionType) { + case MYSQL -> ":json"; + case POSTGRES -> "CAST(:json AS jsonb)"; + }; + } + + /** + * Moves the term links stored under one name onto another. A link the pair already holds under + * the new name is kept, and the stored one deleted. + */ + private static void renameTermLinks( + final Handle handle, final ConnectionType connectionType, final LinkRename rename) { + executeOnTermLinks(handle, deleteDuplicateLinksSql(connectionType), rename); + executeOnTermLinks(handle, renameLinksSql(connectionType), rename); + } + + private static String deleteDuplicateLinksSql(final ConnectionType connectionType) { + return switch (connectionType) { + case MYSQL -> "DELETE stale FROM entity_relationship stale JOIN entity_relationship kept ON" + + sameLinkUnderResolvedType(connectionType) + + " WHERE" + + staleTermLinks(connectionType); + case POSTGRES -> "DELETE FROM entity_relationship stale USING entity_relationship kept WHERE" + + sameLinkUnderResolvedType(connectionType) + + " AND" + + staleTermLinks(connectionType); + }; + } + + private static String renameLinksSql(final ConnectionType connectionType) { + return switch (connectionType) { + case MYSQL -> "UPDATE entity_relationship stale SET stale.relationType = :resolved," + + " stale.json = JSON_SET(COALESCE(stale.json, JSON_OBJECT()), '$.relationType'," + + " :resolved) WHERE" + + staleTermLinks(connectionType); + case POSTGRES -> "UPDATE entity_relationship stale SET relationType = :resolved," + + " json = jsonb_set(COALESCE(stale.json, '{}'::jsonb), '{relationType}'," + + " to_jsonb(CAST(:resolved AS text))) WHERE" + + staleTermLinks(connectionType); + }; + } + + private static String staleTermLinks(final ConnectionType connectionType) { + return " stale.fromEntity = :entity AND stale.toEntity = :entity AND stale.relation = :relation" + + " AND " + + exactRelationType(connectionType, "stale") + + " = :stored"; + } + + // The inequality stops a case-insensitive collation from matching a stale row against itself. + private static String sameLinkUnderResolvedType(final ConnectionType connectionType) { + return " kept.fromId = stale.fromId AND kept.toId = stale.toId AND kept.relation = stale.relation" + + " AND " + + exactRelationType(connectionType, "kept") + + " = :resolved AND kept.relationType <> stale.relationType"; + } + + // MySQL compares byte for byte, so one stored name never matches another in a different case. + private static String exactRelationType(final ConnectionType connectionType, final String alias) { + return switch (connectionType) { + case MYSQL -> "CONVERT(" + alias + ".relationType USING utf8mb4) COLLATE utf8mb4_bin"; + case POSTGRES -> alias + ".relationType"; + }; + } + + private static void executeOnTermLinks( + final Handle handle, final String sql, final LinkRename rename) { + handle + .createUpdate(sql) + .bind("entity", GLOSSARY_TERM) + .bind("relation", Relationship.RELATED_TO.ordinal()) + .bind("stored", rename.storedName()) + .bind("resolved", rename.resolvedName()) + .execute(); + } + + /** + * Points every glossary term link at the stored type its column names, as 2.1.0 did for the links + * it could resolve: the type id and the json 2.1 reads the type from follow the column. + */ + private static void relinkTermLinks(final Handle handle, final ConnectionType connectionType) { + handle + .createUpdate( + switch (connectionType) { + case MYSQL -> MYSQL_RELINK; + case POSTGRES -> POSTGRES_RELINK; + }) + .bind("entity", GLOSSARY_TERM) + .bind("relation", Relationship.RELATED_TO.ordinal()) + .execute(); + } + + // relationType takes the database character set, so it is converted before a binary compare. + private static final String MYSQL_RELINK = + """ + UPDATE entity_relationship relationship + JOIN relationship_type_entity relationship_type + ON relationship_type.name COLLATE utf8mb4_bin + = CONVERT(relationship.relationType USING utf8mb4) COLLATE utf8mb4_bin + SET relationship.relationshipTypeId = relationship_type.id, + relationship.json = JSON_SET( + COALESCE(relationship.json, JSON_OBJECT()), + '$.id', relationship.relationshipId, + '$.relationshipTypeId', relationship_type.id, + '$.sourceTermId', COALESCE( + JSON_UNQUOTE(JSON_EXTRACT(relationship.json, '$.sourceTermId')), relationship.fromId), + '$.relationType', relationship.relationType, + '$.provenance', COALESCE( + JSON_UNQUOTE(JSON_EXTRACT(relationship.json, '$.provenance')), 'Manual'), + '$.status', COALESCE( + JSON_UNQUOTE(JSON_EXTRACT(relationship.json, '$.status')), 'Approved'), + '$.createdBy', COALESCE( + JSON_UNQUOTE(JSON_EXTRACT(relationship.json, '$.createdBy')), 'system'), + '$.createdAt', COALESCE( + CAST(JSON_UNQUOTE(JSON_EXTRACT(relationship.json, '$.createdAt')) AS UNSIGNED), + UNIX_TIMESTAMP() * 1000)) + WHERE relationship.fromEntity = :entity + AND relationship.toEntity = :entity + AND relationship.relation = :relation + AND (relationship.relationshipTypeId IS NULL + OR relationship.relationshipTypeId <> relationship_type.id + OR NOT (CONVERT(JSON_UNQUOTE(JSON_EXTRACT(relationship.json, '$.relationType')) + USING utf8mb4) COLLATE utf8mb4_bin + <=> CONVERT(relationship.relationType USING utf8mb4) COLLATE utf8mb4_bin)) + """; + + private static final String POSTGRES_RELINK = + """ + UPDATE entity_relationship relationship + SET relationshipTypeId = relationship_type.id, + json = COALESCE(relationship.json, '{}'::jsonb) || jsonb_build_object( + 'id', relationship.relationshipId, + 'relationshipTypeId', relationship_type.id, + 'sourceTermId', COALESCE(relationship.json->>'sourceTermId', relationship.fromId), + 'relationType', relationship.relationType, + 'provenance', COALESCE(relationship.json->>'provenance', 'Manual'), + 'status', COALESCE(relationship.json->>'status', 'Approved'), + 'createdBy', COALESCE(relationship.json->>'createdBy', 'system'), + 'createdAt', COALESCE( + (relationship.json->>'createdAt')::bigint, + (extract(epoch from now()) * 1000)::bigint)) + FROM relationship_type_entity relationship_type + WHERE relationship_type.name = relationship.relationType + AND relationship.fromEntity = :entity + AND relationship.toEntity = :entity + AND relationship.relation = :relation + AND (relationship.relationshipTypeId IS DISTINCT FROM relationship_type.id + OR relationship.json->>'relationType' IS DISTINCT FROM relationship.relationType) + """; +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapper.java index 6a9930276def..af0eed89d3e2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapper.java @@ -37,6 +37,7 @@ import org.openmetadata.schema.type.RelationshipPaletteKey; import org.openmetadata.schema.type.RelationshipTypeCategory; import org.openmetadata.schema.type.SemanticReference; +import org.openmetadata.service.util.FullyQualifiedName; /** Converts the pre-2.0 settings contract into governed relationship-type entities. */ public final class LegacyRelationshipTypeMapper { @@ -65,7 +66,7 @@ public RelationshipType map( return new RelationshipType() .withId(RelationshipTypeIds.stableId(configuredType.getName())) .withName(configuredType.getName()) - .withFullyQualifiedName(configuredType.getName()) + .withFullyQualifiedName(FullyQualifiedName.quoteName(configuredType.getName())) .withDisplayName(configuredType.getDisplayName()) .withDescription(description(configuredType)) .withIri(predicate) @@ -95,11 +96,16 @@ private static URI predicate(final GlossaryTermRelationType configuredType) { final URI configuredPredicate = configuredType.getRdfPredicate(); final URI predicate = configuredPredicate == null - ? URI.create(DEFAULT_PREDICATE_BASE + configuredType.getName()) + ? defaultPredicate(configuredType.getName()) : configuredPredicate; return predicate; } + /** The predicate a type gets when it declares none; the name is encoded, as it may hold a space. */ + private static URI defaultPredicate(final String name) { + return URI.create(DEFAULT_PREDICATE_BASE + URLEncoder.encode(name, UTF_8).replace("+", "%20")); + } + private static RelationshipTypeCategory category( final GlossaryTermRelationType configuredType, final URI predicate) { final RelationshipTypeCategory category; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizer.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizer.java index 1087dab1a3f8..00def8590238 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizer.java @@ -26,6 +26,7 @@ import org.openmetadata.schema.entity.data.RelationshipType; import org.openmetadata.schema.type.Include; import org.openmetadata.service.jdbi3.RelationshipTypeRepository; +import org.openmetadata.service.util.FullyQualifiedName; /** Keeps the deprecated settings write endpoint compatible during the 2.0 transition. */ public final class LegacyRelationshipTypeSynchronizer { @@ -64,7 +65,8 @@ private Set softDeletedNames(final List relationshipTy .map(RelationshipType::getName) .filter( name -> { - final RelationshipType existing = repository.findByNameOrNull(name, Include.ALL); + final RelationshipType existing = + repository.findByNameOrNull(FullyQualifiedName.quoteName(name), Include.ALL); return existing != null && Boolean.TRUE.equals(existing.getDeleted()); }) .collect(Collectors.toUnmodifiableSet()); @@ -73,7 +75,8 @@ private Set softDeletedNames(final List relationshipTy private void upsert( final UriInfo uriInfo, final String updatedBy, final RelationshipType relationshipType) { final RelationshipType existing = - repository.findByNameOrNull(relationshipType.getName(), Include.ALL); + repository.findByNameOrNull( + FullyQualifiedName.quoteName(relationshipType.getName()), Include.ALL); if (existing != null) { relationshipType.setId(existing.getId()); relationshipType.setSystemDefined(existing.getSystemDefined()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/RelationshipTypeResolver.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/RelationshipTypeResolver.java index 896ed7508ddc..dbcdc7f63521 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/RelationshipTypeResolver.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/RelationshipTypeResolver.java @@ -35,12 +35,14 @@ public RelationshipTypeResolver(final CollectionDAO.RelationshipTypeDAO relation this.relationshipTypeDAO = relationshipTypeDAO; } + /** By name, quoted as a type's FQN is, so a name holding a dot is one segment, not two. */ public RelationshipType require(final String name) { + final String fqn = FullyQualifiedName.quoteName(name); final RelationshipType relationshipType; try { - relationshipType = named(relationshipTypeDAO.findEntityByName(name, Include.NON_DELETED)); + relationshipType = named(relationshipTypeDAO.findEntityByName(fqn, Include.NON_DELETED)); } catch (EntityNotFoundException exception) { - throw unavailable(name, () -> relationshipTypeDAO.findEntityByName(name, Include.ALL)); + throw unavailable(name, () -> relationshipTypeDAO.findEntityByName(fqn, Include.ALL)); } return relationshipType; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/RelationshipTypeResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/RelationshipTypeResource.java index 03f804e70a26..fbc4abcede3a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/RelationshipTypeResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/RelationshipTypeResource.java @@ -51,6 +51,7 @@ import org.openmetadata.service.resources.Collection; import org.openmetadata.service.resources.EntityResource; import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.FullyQualifiedName; @Path("/v1/relationshipTypes") @Tag( @@ -138,7 +139,8 @@ public Response createOrUpdate( private RelationshipType updateEntity(final CreateRelationshipType request, final String user) { final RelationshipType entity = mapper.createToEntity(request, user); - final RelationshipType existing = repository.findByNameOrNull(request.getName(), Include.ALL); + final RelationshipType existing = + repository.findByNameOrNull(FullyQualifiedName.quoteName(request.getName()), Include.ALL); entity.setId(existing == null ? entity.getId() : existing.getId()); entity.setSystemDefined(existing == null ? false : existing.getSystemDefined()); entity.setProvider(existing == null ? entity.getProvider() : existing.getProvider()); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/OntologyMigrationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/OntologyMigrationTest.java index 228819e11d04..18c3a8d66816 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/OntologyMigrationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/OntologyMigrationTest.java @@ -17,20 +17,24 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URI; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.List; import org.junit.jupiter.api.Test; +import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; import org.openmetadata.schema.configuration.GlossaryTermRelationType; import org.openmetadata.schema.configuration.RelationCardinality; import org.openmetadata.schema.configuration.RelationCategory; import org.openmetadata.schema.entity.data.RelationshipType; import org.openmetadata.schema.type.RelationshipCharacteristic; import org.openmetadata.schema.type.RelationshipTypeCategory; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.ontology.LegacyRelationshipTypeMapper; import org.openmetadata.service.ontology.RelationshipTypeIds; +import org.openmetadata.service.ontology.RelationshipTypeValidator; class OntologyMigrationTest { private static final LegacyRelationshipTypeMapper MAPPER = @@ -80,6 +84,233 @@ void leavesUnconfiguredCardinalityAbsent() { assertNull(relationshipType.getCardinality()); } + @Test + void createsTheInverseTypeAFreeTextInverseNamed() { + ObjectNode settings = + settingsOf(baseType().withName("dependsOn").withInverseRelation("Dependency Of")); + + List renames = + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationSettings repaired = toSettings(settings); + GlossaryTermRelationType created = typeNamed(repaired, "dependencyOf"); + assertEquals("Dependency Of", created.getDisplayName()); + assertEquals("dependsOn", created.getInverseRelation()); + assertEquals(RelationCategory.ASSOCIATIVE, created.getCategory()); + assertEquals(Boolean.FALSE, created.getIsSystemDefined()); + assertEquals("dependencyOf", typeNamed(repaired, "dependsOn").getInverseRelation()); + assertEquals( + List.of(new OntologyMigration.InverseRename("Dependency Of", "dependencyOf")), renames); + List mapped = MAPPER.map(repaired, "migration-test"); + assertEquals("dependencyOf", typeIn(mapped, "dependsOn").getInverse().getName()); + assertEquals("dependsOn", typeIn(mapped, "dependencyOf").getInverse().getName()); + } + + @Test + void createdInverseMirrorsTheDirectionalConstraints() { + ObjectNode settings = + settingsOf( + baseType() + .withName("dependsOn") + .withInverseRelation("Dependency Of") + .withCardinality(RelationCardinality.ONE_TO_MANY) + .withIsFunctional(true) + .withIsTransitive(true) + .withDomain(List.of("Source.Class")) + .withRange(List.of("Target.Class"))); + + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationType created = typeNamed(toSettings(settings), "dependencyOf"); + assertEquals(RelationCardinality.MANY_TO_ONE, created.getCardinality()); + assertEquals(Boolean.TRUE, created.getIsInverseFunctional()); + assertEquals(Boolean.FALSE, created.getIsFunctional()); + assertEquals(Boolean.TRUE, created.getIsTransitive()); + assertEquals(List.of("Target.Class"), created.getDomain()); + assertEquals(List.of("Source.Class"), created.getRange()); + } + + @Test + void resolvesAnInverseThatNamesAnExistingTypeInAnotherCase() { + ObjectNode settings = + settingsOf( + baseType().withName("parentOf").withInverseRelation("ChildOf"), + baseType().withName("childOf").withInverseRelation("parentOf")); + + List renames = + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationSettings repaired = toSettings(settings); + assertEquals(2, repaired.getRelationTypes().size(), "no type is created for a known type"); + assertEquals("childOf", typeNamed(repaired, "parentOf").getInverseRelation()); + assertEquals(List.of(new OntologyMigration.InverseRename("ChildOf", "childOf")), renames); + } + + @Test + void anInverseMatchingOnlyAnotherTypesDisplayNameGetsItsOwnType() { + ObjectNode settings = + settingsOf( + baseType().withName("controls").withInverseRelation("controlledBy"), + baseType() + .withName("controlledBy") + .withDisplayName("Controlled By") + .withInverseRelation("controls"), + baseType().withName("regulates").withInverseRelation("Controlled By")); + + List renames = + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationSettings repaired = toSettings(settings); + GlossaryTermRelationType created = typeNamed(repaired, "controlledBy2"); + assertEquals("Controlled By", created.getDisplayName()); + assertEquals("regulates", created.getInverseRelation()); + assertEquals("controlledBy2", typeNamed(repaired, "regulates").getInverseRelation()); + assertEquals("controls", typeNamed(repaired, "controlledBy").getInverseRelation()); + assertEquals( + List.of(new OntologyMigration.InverseRename("Controlled By", "controlledBy2")), renames); + assertEquals(4, MAPPER.map(repaired, "migration-test").size()); + } + + @Test + void typesThatNameTheSameMissingInverseShareOneCreatedType() { + ObjectNode settings = + settingsOf( + baseType().withName("feeds").withInverseRelation("Fed By"), + baseType().withName("supplies").withInverseRelation("Fed By")); + + List renames = + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationSettings repaired = toSettings(settings); + assertEquals(3, repaired.getRelationTypes().size()); + assertEquals("fedBy", typeNamed(repaired, "supplies").getInverseRelation()); + assertEquals("feeds", typeNamed(repaired, "fedBy").getInverseRelation()); + assertEquals(List.of(new OntologyMigration.InverseRename("Fed By", "fedBy")), renames); + assertEquals(3, MAPPER.map(repaired, "migration-test").size()); + } + + @Test + void generatedNameNeverCollidesWithAnExistingType() { + ObjectNode settings = + settingsOf( + baseType().withName("fedBy").withDisplayName("Supplied From"), + baseType().withName("feeds").withInverseRelation("Fed-By!"), + baseType().withName("reports").withInverseRelation("2nd Line")); + + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationSettings repaired = toSettings(settings); + assertEquals("fedBy2", typeNamed(repaired, "feeds").getInverseRelation()); + assertEquals("Fed-By!", typeNamed(repaired, "fedBy2").getDisplayName()); + assertEquals("inverseOfReports", typeNamed(repaired, "reports").getInverseRelation()); + } + + @Test + void leavesResolvedInversesAloneAndDropsABlankOne() { + ObjectNode settings = + settingsOf( + baseType().withName("broader").withInverseRelation("narrower"), + baseType().withName("narrower").withInverseRelation("broader"), + baseType().withName("mentions").withInverseRelation(" ")); + + List renames = + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationSettings repaired = toSettings(settings); + assertTrue(renames.isEmpty()); + assertEquals(3, repaired.getRelationTypes().size()); + assertEquals("narrower", typeNamed(repaired, "broader").getInverseRelation()); + assertNull(typeNamed(repaired, "mentions").getInverseRelation()); + } + + @Test + void aSymmetricTypesFreeTextInverseIsTheTypeItself() { + ObjectNode settings = + settingsOf( + baseType().withName("peerOf").withIsSymmetric(true).withInverseRelation("Peer Of")); + + List renames = + OntologyMigration.resolveUnresolvedInverses(settings); + + GlossaryTermRelationSettings repaired = toSettings(settings); + assertEquals(1, repaired.getRelationTypes().size(), "no second type is created"); + assertEquals("peerOf", typeNamed(repaired, "peerOf").getInverseRelation()); + assertEquals(List.of(new OntologyMigration.InverseRename("Peer Of", "peerOf")), renames); + MAPPER.map(repaired, "migration-test").forEach(RelationshipTypeValidator::validate); + } + + @Test + void aNameDefinedTwiceKeepsTheSystemDefinitionElseTheFirst() { + ObjectNode settings = + settingsOf( + baseType().withName("relatedTo").withDescription("custom copy"), + baseType().withName("owns").withDescription("first"), + baseType().withName("relatedTo").withIsSystemDefined(true).withDescription("system"), + baseType().withName("owns").withDescription("second")); + + List duplicates = OntologyMigration.dropDuplicateNames(settings); + + GlossaryTermRelationSettings deduplicated = toSettings(settings); + assertEquals(List.of("relatedTo", "owns"), duplicates); + assertEquals( + List.of("relatedTo", "owns"), + deduplicated.getRelationTypes().stream().map(GlossaryTermRelationType::getName).toList()); + assertEquals("system", typeNamed(deduplicated, "relatedTo").getDescription()); + assertEquals("first", typeNamed(deduplicated, "owns").getDescription()); + } + + @Test + void everyTypeTheRepairCreatesPassesTheChecksA21SaveRuns() { + ObjectNode settings = + settingsOf( + baseType().withName("dependsOn").withInverseRelation("Dependency Of"), + baseType() + .withName("owns") + .withIsAsymmetric(true) + .withIsFunctional(true) + .withInverseRelation("Owned By")); + + OntologyMigration.resolveUnresolvedInverses(settings); + + MAPPER.map(toSettings(settings), "migration-test").forEach(RelationshipTypeValidator::validate); + } + + @Test + void aSecondRunFindsNothingToRepair() { + ObjectNode settings = + settingsOf(baseType().withName("dependsOn").withInverseRelation("Dependency Of")); + OntologyMigration.resolveUnresolvedInverses(settings); + String afterFirstRun = settings.toString(); + + List renames = + OntologyMigration.resolveUnresolvedInverses(settings); + + assertTrue(renames.isEmpty()); + assertEquals(afterFirstRun, settings.toString()); + } + + private static ObjectNode settingsOf(GlossaryTermRelationType... relationTypes) { + return (ObjectNode) + JsonUtils.valueToTree( + new GlossaryTermRelationSettings().withRelationTypes(List.of(relationTypes))); + } + + private static GlossaryTermRelationSettings toSettings(ObjectNode settings) { + return JsonUtils.convertValue(settings, GlossaryTermRelationSettings.class); + } + + private static GlossaryTermRelationType typeNamed( + GlossaryTermRelationSettings settings, String name) { + return settings.getRelationTypes().stream() + .filter(type -> name.equals(type.getName())) + .findFirst() + .orElseThrow(); + } + + private static RelationshipType typeIn(List types, String name) { + return types.stream().filter(type -> name.equals(type.getName())).findFirst().orElseThrow(); + } + private static GlossaryTermRelationType baseType() { return new GlossaryTermRelationType() .withName("prescribes") diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepairTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepairTest.java new file mode 100644 index 000000000000..bad7f14a02b3 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v212/RelationshipTypeRepairTest.java @@ -0,0 +1,235 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.migration.utils.v212; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; +import org.openmetadata.schema.configuration.GlossaryTermRelationType; +import org.openmetadata.schema.configuration.RelationCategory; +import org.openmetadata.schema.entity.data.RelationshipType; +import org.openmetadata.schema.type.RelationshipCharacteristic; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.ontology.LegacyRelationshipTypeMapper; +import org.openmetadata.service.ontology.RelationshipTypeValidator; + +class RelationshipTypeRepairTest { + private static final LegacyRelationshipTypeMapper MAPPER = + new LegacyRelationshipTypeMapper( + Clock.fixed(Instant.parse("2026-07-18T00:00:00Z"), ZoneOffset.UTC)); + private static final URI EXACT_MATCH = + URI.create("http://www.w3.org/2004/02/skos/core#exactMatch"); + private static final URI SUB_CLASS_OF = + URI.create("http://www.w3.org/2000/01/rdf-schema#subClassOf"); + private static final URI SHARED = URI.create("https://example.org/feeds"); + private static final Map SEEDS = RelationshipTypeRepair.SEED_PREDICATES; + + @Test + void everyStoredTypeCanBeSavedAgainAndHoldsAPredicateOfItsOwn() { + final List types = pojos(planned(storedBy210())); + + types.forEach(RelationshipTypeValidator::validate); + final List predicates = + types.stream().map(type -> type.getRdfPredicate().toString()).toList(); + assertEquals(predicates.size(), Set.copyOf(predicates).size(), "no predicate is shared"); + types.forEach( + type -> + assertTrue( + !SEEDS.containsKey(type.getRdfPredicate().toString()) + || SEEDS.get(type.getRdfPredicate().toString()).equals(type.getName()), + type.getName() + " holds no other seed's predicate")); + } + + @Test + void eachShapeIsRepairedTheWayItsPartnerAndSeedExpect() { + final Map repaired = byName(pojos(planned(storedBy210()))); + + assertEquals("peerOf", repaired.get("peerOf").getInverse().getName()); + assertEquals(ontology("dependsOnRel"), repaired.get("dependsOnRel").getRdfPredicate()); + assertEquals(EXACT_MATCH, repaired.get("synonym").getRdfPredicate(), "the seed keeps its own"); + assertEquals(ontology("sameAs"), repaired.get("sameAs").getRdfPredicate()); + assertEquals(SHARED, repaired.get("feedsA").getRdfPredicate(), "the first by name keeps it"); + assertEquals(ontology("feedsB"), repaired.get("feedsB").getRdfPredicate()); + assertEquals(ontology("isA"), repaired.get("isA").getRdfPredicate(), "subClassOf can seed"); + assertFalse(has(repaired.get("oddFlags"), RelationshipCharacteristic.SYMMETRIC)); + assertFalse(has(repaired.get("oddFlags"), RelationshipCharacteristic.ASYMMETRIC)); + assertFalse(has(repaired.get("ownInverse"), RelationshipCharacteristic.ASYMMETRIC)); + assertEquals(1, repaired.get("owns").getCardinality().getSourceMax()); + assertEquals("\"part.of\"", repaired.get("part.of").getFullyQualifiedName()); + } + + @Test + void linksStoredUnderNoTypePointAtOneAndABlankOneReadsAsRelatedTo() { + final RelationshipTypeRepair.Plan plan = + RelationshipTypeRepair.plan( + storedBy210(), Set.of("controls", "Holder Of", "holder of", "", "CONTROLS")); + + final RelationshipType holderOf = byName(pojos(plan.created())).get("holderOf"); + assertEquals("Holder Of", holderOf.getDisplayName()); + RelationshipTypeValidator.validate(holderOf); + assertEquals( + 1, plan.created().size(), "a type named in another case, or created for one, is reused"); + assertEquals( + Set.of( + new RelationshipTypeRepair.LinkRename("", "relatedTo"), + new RelationshipTypeRepair.LinkRename("CONTROLS", "controls"), + new RelationshipTypeRepair.LinkRename("Holder Of", "holderOf"), + new RelationshipTypeRepair.LinkRename("holder of", "holderOf")), + Set.copyOf(plan.renames())); + } + + @Test + void aLinkTextMatchingOnlyAnotherTypesDisplayNameGetsItsOwnType() { + final RelationshipTypeRepair.Plan plan = + RelationshipTypeRepair.plan(storedBy210(), Set.of("Controls Of")); + + final RelationshipType controlsOf = byName(pojos(plan.created())).get("controlsOf"); + assertEquals("Controls Of", controlsOf.getDisplayName()); + RelationshipTypeValidator.validate(controlsOf); + assertEquals( + List.of(new RelationshipTypeRepair.LinkRename("Controls Of", "controlsOf")), + plan.renames()); + } + + @Test + void aTypeTheRepairDoesNotNeedIsLeftAsStored() { + final RelationshipTypeRepair.Plan plan = RelationshipTypeRepair.plan(storedBy210(), Set.of()); + + final Set changed = + pojos(plan.changed()).stream().map(RelationshipType::getName).collect(Collectors.toSet()); + assertEquals( + Set.of( + "peerOf", + "dependsOnRel", + "sameAs", + "feedsB", + "isA", + "oddFlags", + "ownInverse", + "owns", + "part.of"), + changed); + } + + @Test + void aSecondRunFindsNothingToRepair() { + final List types = new ArrayList<>(planned(storedBy210())); + final RelationshipTypeRepair.Plan first = + RelationshipTypeRepair.plan(types, Set.of("Holder Of")); + types.addAll(first.created()); + + final RelationshipTypeRepair.Plan second = + RelationshipTypeRepair.plan(reloaded(types), Set.of("holderOf")); + + assertTrue(second.changed().isEmpty()); + assertTrue(second.created().isEmpty()); + assertTrue(second.renames().isEmpty()); + } + + /** The types as the released 2.1.0 conversion stored each shape 2.0 accepted. */ + private static List storedBy210() { + final List types = + new ArrayList<>( + MAPPER.map( + new GlossaryTermRelationSettings() + .withRelationTypes( + List.of( + system("relatedTo").withIsSymmetric(true), + system("synonym").withIsSymmetric(true).withRdfPredicate(EXACT_MATCH), + custom("controls").withInverseRelation("controlledBy"), + custom("controlledBy") + .withDisplayName("Controls Of") + .withInverseRelation("controls"), + custom("peerOf").withIsSymmetric(true).withInverseRelation("relatedTo"), + custom("dependsOnRel").withRdfPredicate(URI.create("dependsOn")), + custom("sameAs").withRdfPredicate(EXACT_MATCH), + custom("feedsA").withRdfPredicate(SHARED), + custom("feedsB").withRdfPredicate(SHARED), + custom("isA").withRdfPredicate(SUB_CLASS_OF), + custom("oddFlags").withIsSymmetric(true).withIsAsymmetric(true), + custom("ownInverse") + .withIsAsymmetric(true) + .withInverseRelation("ownInverse"), + custom("owns").withIsFunctional(true), + custom("part.of"))), + "migration-test")); + // 2.1.0 stored the bare name as the FQN; a functional type with no limit is any other writer's. + byName(types).get("part.of").setFullyQualifiedName("part.of"); + byName(types).get("owns").setCardinality(null); + return types.stream().map(type -> (ObjectNode) JsonUtils.valueToTree(type)).toList(); + } + + private static List planned(final List types) { + final List rows = new ArrayList<>(types); + RelationshipTypeRepair.plan(rows, Set.of()); + return rows; + } + + /** The rows as the next run reads them back from the table. */ + private static List reloaded(final List types) { + return types.stream() + .map(type -> (ObjectNode) JsonUtils.readTree(type.toString())) + .collect(Collectors.toCollection(ArrayList::new)); + } + + private static List pojos(final List rows) { + return rows.stream() + .map(row -> JsonUtils.readValue(row.toString(), RelationshipType.class)) + .toList(); + } + + private static GlossaryTermRelationType system(final String name) { + return custom(name).withIsSystemDefined(true); + } + + private static GlossaryTermRelationType custom(final String name) { + return new GlossaryTermRelationType() + .withName(name) + .withDisplayName(name) + .withDescription(name) + .withCategory(RelationCategory.ASSOCIATIVE) + .withIsCrossGlossaryAllowed(true) + .withIsSystemDefined(false); + } + + private static Map byName(final List types) { + final Map byName = new HashMap<>(); + Stream.of(types).flatMap(List::stream).forEach(type -> byName.put(type.getName(), type)); + return byName; + } + + private static boolean has( + final RelationshipType type, final RelationshipCharacteristic characteristic) { + return type.getCharacteristics().contains(characteristic); + } + + private static URI ontology(final String name) { + return URI.create("https://open-metadata.org/ontology/" + name); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapperTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapperTest.java index 542dcc11ebc0..5a8500acc9aa 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapperTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeMapperTest.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.net.URI; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -73,6 +74,24 @@ void usesTheInjectedClockForDeterministicMigrationRows() { assertEquals(ProviderType.USER, mapped.getProvider()); } + @Test + void aNameWithASpaceGetsAnEncodedDefaultPredicate() { + RelationshipType mapped = mapper.map(type("held by", null), "admin"); + + assertEquals( + URI.create("https://open-metadata.org/ontology/held%20by"), mapped.getRdfPredicate()); + assertEquals("held by", mapped.getFullyQualifiedName()); + } + + @Test + void aDottedNameIsStoredUnderTheQuotedFqnItIsLookedUpBy() { + RelationshipType mapped = mapper.map(type("part.of", null), "admin"); + + assertEquals("\"part.of\"", mapped.getFullyQualifiedName()); + assertEquals( + URI.create("https://open-metadata.org/ontology/part.of"), mapped.getRdfPredicate()); + } + private static GlossaryTermRelationType type(String name, RelationCardinality cardinality) { return new GlossaryTermRelationType() .withName(name) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizerTest.java index ea87189f8a91..0e7c62dd2a40 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizerTest.java @@ -100,6 +100,17 @@ void upsertPreservesIdentityFieldsOfExistingType() { assertSame(reviewers, persisted.getReviewers()); } + @Test + void upsertFindsADottedNameUnderItsQuotedFqn() { + UUID existingId = UUID.randomUUID(); + when(repository.findByNameOrNull("\"part.of\"", Include.ALL)) + .thenReturn(existing(existingId, "part.of", false)); + + synchronizer.synchronize(null, settings("part.of"), null, UPDATED_BY); + + assertEquals(existingId, capturePersisted().getId()); + } + @Test void upsertOfNewTypeDoesNotCopyIdentityFields() { when(repository.findByNameOrNull("governs", Include.ALL)).thenReturn(null); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/RelationshipTypeResolverTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/RelationshipTypeResolverTest.java index bbf94cbafae8..78e48c1c92a1 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/RelationshipTypeResolverTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/RelationshipTypeResolverTest.java @@ -52,6 +52,15 @@ private RelationshipType type(final String name) { return new RelationshipType().withName(name); } + @Test + void requireLooksUpADottedNameAsOneQuotedSegment() { + RelationshipType partOf = type("part.of"); + when(relationshipTypeDAO.findEntityByName("\"part.of\"", Include.NON_DELETED)) + .thenReturn(partOf); + + assertSame(partOf, resolver().require("part.of")); + } + @Test void requireByNameReturnsTypeFromDao() { RelationshipType broader = type("broader"); From 48ee90a4fcc075d62ff7e8217ec6ca67deb798a1 Mon Sep 17 00:00:00 2001 From: sonika-shah <58761340+sonika-shah@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:11:21 +0530 Subject: [PATCH 2/2] Map the migration IT directory to migrations-seed-data, as on main --- .github/java-tests/impact-map.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/java-tests/impact-map.json b/.github/java-tests/impact-map.json index 18bb66382d51..1d7165a108e9 100644 --- a/.github/java-tests/impact-map.json +++ b/.github/java-tests/impact-map.json @@ -1108,6 +1108,7 @@ ], "tests": [ "*Migration*IT", + "org/openmetadata/it/tests/migration/**", "*SeedData*IT", "*Operations*IT", "*DbTune*IT"